const cliente = {
nome: "Andre",
idade: 36,
cpf: "123.456.789.10",
email: "andre#gmail.com"
}
const chaves = ["nome", "idade", "cpf", "email"];
const clienteString = chaves.reduce((acum, curr) => acum += curr + ":" + cliente[curr] + ";")
console.log(clienteString);
the current output is: **nome**idade:36;cpf:123.456.789.10;email:andre#gmail.com;
the value of the key "nome:" is not being considered in the string
it should output this: nome:Andre;idade:36;cpf:123.456.789-10;email:andre#gmail.com;
what am i doing wrong?
This is a simpler version that does what you want:
const cliente = {
nome: "Andre",
idade: 36,
cpf: "123.456.789.10",
email: "andre#gmail.com",
};
console.log(
Object.entries(cliente)
.map(([key, value]) => `${key}:${value};`)
.join("")
);
Object.entries returns an array of ["key", "value"]. Then we map over that and turn it into an array of "key:value;". Then we join the array of "key:value;" into a string.
Related
I need to create an Dynamic key value pairs from the existing object
const balanceScheule = 1255;
const reqCost = [{Labour Cost: "1555"}, {Material Cost: "1575"}]; // key is dynamic and keeps on changing
const amfqtyCost = 1416;
Here the logic is to create an new array of object and subtract the amfqtyCost from reqCost
Logic i Have written
reqCost.forEach(element => {
const adjustedAmount = Object.entries(element).map((m) => {
let adjustedAmount = parseInt(m[1]) - amfqtyCost;
return adjustedAmount;
});
// console.log(...adjustedAmount)
});
this return 139 and 159 which is (1555 - 1416 = 139) and (1575 1416 = 159) respectively
Expected output :
[{Labour Cost: "139"}, {Material Cost: "159"}]
How to do i merge ?
You just need to return the updated object from within map function. Also for the outer iteration use map instead of forEach to return the final result
const balanceScheule = 1255;
const reqCost = [{
'Labour Cost': "1555",
}, {
'Material Cost': "1575",
}]; // key is dynamic and keeps on changing
const amfqtyCost = 1416;
const updatedData = reqCost.map(element => {
return Object.assign({}, ...Object.entries(element).map(([key, value]) => {
let adjustedAmount = parseInt(value) - amfqtyCost;
return {
[key]: String(adjustedAmount)
};
}));
});
console.log(updatedData);
You can do something like this:
const reqCost = [{
'Labour Cost': "1555"
}, {
'Material Cost': "1575"
}];
const amfqtyCost = 1416;
const adjustedCost = reqCost.map(cost => ({
[Object.keys(cost)[0]]: (parseInt(Object.values(cost)[0]) - amfqtyCost).toFixed(0)
}));
console.log(adjustedCost);
// OR, if you prefer to be a bit more verbose:
const adjustedCost2 = reqCost.map(cost => {
const [key, value] = Object.entries(cost)[0];
return {
[key]: (parseInt(value) - amfqtyCost).toFixed(0)
}
});
console.log(adjustedCost2);
You can reverse the Object.entries
{ key : value } => [ [ key, value ] ]
transformation by using Object.fromEntries
[ [ key, value ] ] => { key : value }
the code will look like this
reqCost.map((obj) =>
Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
key,
parseInt(value) - amfqtyCost,
])
)
);
I have this string:
posts{id,title},posts2{id,title}
I'd like to transform it to an object:
{
posts: [
'id',
'title'
],
posts2: [
'id',
'title'
]
}
How can I do this?
Given that the string will be valid with the specified format:
You can split the string into pairs of key - list items.
Then, iterate over them and insert each into an object as follows:
const stringify = string => {
const obj = {};
if(string) {
const pairs = string.substring(0,string.length-1).split('},');
pairs.forEach(pair => {
const [key,value] = pair.split('{');
obj[key] = value.split(",").filter(String);
});
}
return obj;
}
console.log( stringify('posts{id,title},posts2{id,title}') );
console.log( stringify('posts{id,title}') );
console.log( stringify('posts{}') );
console.log( stringify('') );
This snippet works until you work with a 1-level object. If you need to parse nested object, you've to slightly refactor it.
const input = 'posts{id,title},posts2{id,title}';
const parse = (input) => {
return input
.replaceAll('{', '[')
.replaceAll('}', ']')
.replaceAll('],', '] , ')
.split(' , ')
.reduce((_, item) => {
const key = item.split('[')[0];
const value = item
.replace(`${key}[`, '')
.replace(']', '')
.split(',')
return {
..._,
[key]: value
};
}, {})
};
const parsed = parse(input);
Anyway I don't know what's the benefit of dealing with this notation.
I have array with object in localstorage
image
Some a function return object with new data. I need to write new data to object in localstorage (identify by ID).
I tried but... See my code below
const result = {
type: 'mobile',
id: 'tsy152ivm',
score: 55
}
const links = JSON.parse(localStorage.getItem('links'));
const item = links.find(item => item.id === result.id);
//localStorage.setItem('links', JSON.stringify(item));
You should get data from the storage, find an index of the target item, merge old object with a new one and store the result at the specific index, and then set the whole array at the same key. Here is a part of the most important steps:
const newData = {
id: 'ID_2',
NEW_DATA: 'NEW_DATA'
};
/**
* Get old data from storage
*/
const dataFromStorage = JSON.parse(localStorage.getItem('links'));
/**
* Merge old object with a new one (find by ID)
*/
const index = dataFromStorage.findIndex(d => d.id === newData.id);
dataFromStorage[index] = Object.assign({}, dataFromStorage[index], newData)
/**
* Update full array in storage
*/
localStorage.setItem('links', JSON.stringify(dataFromStorage));
And here is a link to JSFIDDLE with fully working example (check the local storage after execution).
Use .findIndex() to find the index of the object you want to modify, and use Object.assign() to update the object's properties.
let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]
const result = {
type: 'mobile',
id: 'tsy152ivm',
score: 55
}
const index = arr.findIndex(item => item.id === result.id);
const updated = [...arr.slice(0, index),Object.assign({}, arr[index], { id: result.id, name: 'Samantha' }),
...arr.slice(index + 1)
]
console.log(updated);
or just modify the object directly, using an index.
let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]
const result = {
type: 'mobile',
id: 'tsy152ivm',
score: 55
}
const index = arr.findIndex(item => item.id === result.id);
arr[index] = Object.assign({}, arr[index], { name: 'Samantha'})
console.log(arr);
I have an array of objects. I want to get the key and value and print the data. eg. I have id, username and password and I want the username and password.
[
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
The output should be
name : admin
password : admin,
name : user
password : user,
name : superadmin
password : superadmin
To iterate key values dynamically, you have to iterate object.
let arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
];
arr.forEach((item, i) => {
for(let key in item) {
console.log(`${key}: ${item[key]}`);
}
});
If you would like to display only name and password, then you can add a condition.
arr.forEach((item, i) => {
for(let key in item) {
if (key === 'name' || key === "password") {
console.log(`${key}: ${item[key]}`);
}
}
});
Given the array you have, you simply need to loop through it:
var arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.password);
})
let data = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
];
var out_data = data.reduce((a, b) => a + 'name: ' + b.name + ', password: ' + b.password + ' ', '');
console.log(out_data);
var arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
[![enter image description here][1]][1]
Loop through the array
arr.forEach(function(data) {
console.log('name', data.name);
console.log('password', data.password);
})
[1]: https://i.stack.imgur.com/uYA9i.png
I am trying to search easy function on Lodash.js for joining values by given key or something...
Example:
const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
Expected results:
Mr. John Due
Any function like _.join() but better and I can do something like..
_.joinX(obj, ['title', 'firstname', 'lastname'], ' ')
Why not just...?
obj.title + ' ' + obj.firstname + ' ' + obj.lastname
Because sometimes my object is so long like... (And I will not give more variable)
obj.current.user.info.title + ' ' + obj.current.user.info.firstname + ' ' + obj.current.user.info.lastname
You can port the following to Lodash.
const joinByKeys = (obj = {}, props = [], separator = '') => {
// empty array.
let arr = [];
// push props to array
props.forEach(p => arr.push(obj[p]))
// return the joined array.
return arr.join(separator);
}
const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
console.log( joinByKeys(obj, ['title', 'firstname', 'lastname'], ' ') );
I think I got it:
const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
let name = _(obj).pick(['title', 'firstname', 'lastname']).values().join(' ')
console.log(name)
Not really special function as I expected but have to run tho Lodash's functions a bit