Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to convert the array to map,
The array looks like :
var array = [{
"id" : 123
}, {
"id" : 456
}, {
"id" : 789
}];
The final object I'm trying to build should look like :
var result = {
"123": { id: 123 } ,
"456": { id: 456 } ,
"789": { id: 789 }
};
Any efficient way to implement it will be appreciated :)
Thanks
var array = [
{
"id": 123,
"otherProp": "true"
},
{
"id": 456,
"otherProp": "false"
},
{
"id": 789,
"otherProp": "true"
}
];
var result = array.reduce(function (acc, cur, i) {
acc[cur.id] = cur;
return acc;
}, {});
console.log(result);
Use javaScript reduce
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Use reduce
var array = [{
"id" : 123
}, {
"id" : 456
}, {
"id" : 789
}];
var expectedValue = {
"123": { id: 123 } ,
"456": { id: 456 } ,
"789": { id: 789 }
};
var result = array.reduce( (acc, c) => (acc[ c.id ] = c, acc) ,{});
console.log('result : ', result);
console.log('(JSON.stringify(expectedValue) === JSON.stringify(result)) ? ', (JSON.stringify(expectedValue) === JSON.stringify(result)));
.as-console-wrapper { max-height: 100%!important; top: 0; }
Explanation
Use reduce to iterate and initialize the accumulator to {}
Set the key as id of item of every iteration c and value as c itself.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
i have this array
const names = [
{ name: 'Anna' },
{ num: 27 },
{ name: 'Valeria', age: 20},
{ secondname: 'Wilson' },
{ age: 12, name: 'Max' },
{ weight:'50kg', height: '172cm', name: 'Nick' }
]
using reduce i need to create new array that contains all names from initial array
i made like this, but i think it is bad
let allNames = names.reduce((previousValue, names) =>{
return previousValue + names.name},[])
console.log(allNames)
i did
allName.push(ar.name);
return allName;
}, []);
console.log(names);```
Array.reduce()
You have multiple options. You can use Array.reduce to merge them all into one array. You just need to check if name is defined.
names.reduce((allNames, person) => {
if (person.name) {
return [...allNames, person.name];
}
return allNames;
}, []);
Array.forEach()
Same for Array.forEach:
const allNames = [];
names.forEach((person) => {
if (person.name) {
allNames.push(person.name);
}
});
allNames;
Instead, I would recommend using Array.filter to remove all people without a name and map (Array.map) over them, to just return the names.
In terms of runtime, this would require you to loop twice over the array, but I think this is way more readable
Array.filter / Array.map
names
.filter((person) => person.name)
.map((person) => person.name);
Using reduce by including a check for objects that don't have the name property and an empty array as initial value:
const names = [
{ name: 'Anna' },
{ num: 27 },
{ name: 'Valeria', age: 20},
{ secondname: 'Wilson' },
{ age: 12, name: 'Max' },
{ weight:'50kg', height: '172cm', name: 'Nick' }
]
const reduceResult = names.reduce((previous, current) => {
if(current.name)
{
previous.push(current.name);
}
return previous;
}
,
[]);
console.log(reduceResult);
/*
[
"Anna",
"Valeria",
"Max",
"Nick"
]
*/
Using map, you will have undefined for objects that don't have a name property:
const mapResult = names.map(x => x.name);
console.log(mapResult);
/*
[
"Anna",
undefined,
"Valeria",
undefined,
"Max",
"Nick"
]
*/
filter + map can also be used but performance talking reduce is a better choice.
const filterMapResult = names.filter(({name}) => !!name).map(x => x.name);
console.log(filterMapResult);
/*
[
"Anna",
"Valeria",
"Max",
"Nick"
]
*/
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I want to convert data object from:
let data = {
"data.name" : "michael",
"data.email" : "michael#xsx.com",
"person.gender" : "male"
}
into
{
"data" : {
"name": "michael",
"email": "michael#xsx.com"
},
"person" : {
"gender": "male"
}
}
I tried a loop and trying to split key:
let newdata = new Object()
for (const property in datas) {
let key = `${property.split(".")[0]}`
let subkey = `${property.split(".")[1]}`
newdata['key'] = key;
newdata['value'] = {subkey: `${datas[property]}`};
console.log(newdata);
}
The result looks like this:
"data" : {
"name" : {
"michael"
}
},
"data" : {
"email" : {
"michael#xsxx.com"
}
},
"person" : {
"gender" : {
"male"
}
}
What's next?
You can use Object.entries to get the key/value pairs from your existing data, then use reduce to convert that into a new object with the split keys forming a nested object:
const data = {
"data.name" : "michael",
"data.email" : "michael#xsx.com",
"person.gender" : "male"
}
const result = Object.entries(data).reduce((acc, [key, value]) => {
[key, subkey] = key.split('.')
acc[key] = acc[key] || {}
acc[key][subkey] = value
return acc
}, {})
console.log(result)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a JSON object in the below format which I want to convert into a JSON array. I have tried multiple ways to achieve this, but I can not get success.
{
"name":{
"0":"mike",
"1":"george",
"2":"Andrew"
},
"category":{
"0":"A",
"1":"B",
"2":"C"
}
}
The output would be like this:
{
"0":{
"name":"mike",
"category":"A"
},
"1":{
"name":"george",
"category":"B"
},
"2":{
"name":"andrew",
"category":"C"
}
}
I am new to JSON. How can I achieve this?
You can make use of Object.keys and Object.entries
const obj = {
name: {
"0": "mike",
"1": "george",
"2": "Andrew",
},
category: {
"0": "A",
"1": "B",
"2": "C",
},
};
const props = Object.keys(obj);
const result = props.reduce((acc, key) => {
Object.entries(obj[key]).forEach(([k, v]) => {
if (!acc[k]) acc[k] = Object.fromEntries(props.map((p) => [p, ""]));
acc[k][key] = v;
});
return acc;
}, {});
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hi I want to delete key in array
here is my array
const data = [ { id: "2" } , { id: "4" } ]
I want ouput
['2','4']
here is what i try
data.map(function(item) {
//I return only item.id but output still not change
return item.id
})
That's because .map() method returns a new array, it does not alternate the current array. You need to store the returned array in another variable to get the required output like:
const data = [ { id: "2" } , { id: "4" } ]
const res = data.map(x => x.id)
console.log( res )
Or, using same variable:
let data = [ { id: "2" } , { id: "4" } ]
data = data.map(x => x.id)
console.log( data )
Map returns new array and do not alter source array. so you need to assign the result to a new variable.
const data = [{
id: "2"
}, {
id: "4"
}];
const output = data.map(function(item) {
return item.id
})
console.log(output)
Something like this? We map the key to a number and return it.
const data = [ { id: "2" } , { id: "4" } ];
var result = Object.keys(data).map(function (key) {
return Number(key);
});
console.log(result);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to make addition using NodeJS in an array JSON and then return the altered JSON like this, I need also check if key exist or not to avoid exceptions:
JSON:
{
"cmd": [
{
"sales": [
{
"qte1": "2",
"qte2": "3",
"someString": "test
},
{
"qte1": "66",
"someAttribute": "test "
},
{
"qte2": "77",
"toto": "tata"
}
]
}
]
}
target JSON:
{
"cmd": [
{
"sales": [
{
"qte1": "2",
"qte2": "3",
"somme": "5"
},
{
"qte1": "66",
"somme": "66"
},
{
"qte2": "77",
"somme": "77"
}
]
}
]
}
I need to add the two key qte1 et qte2
would you have any propositions ?
Best regards
Seems like you just want the sum of the existing keys, should be pretty simple using a couple .map commands and a .reduce:
return json.cmd.map(function(salesList) {
return salesList.sales.map(function(sale) {
var keysToAdd = ["qte1", "qte2"];
sale.somme = Object.keys(sale).reduce(function(total, key) {
return total += keysToAdd.indexOf(key) > -1 ? +sale[key] : 0;
}, 0);
return sale;
});
});
Demo: https://jsfiddle.net/x294yt1h/
const data =
{
"cmd": [
{
"sales": [
{
"qte1": "2",
"qte2": "3"
},
{
"qte1": "66"
},
{
"qte2": "77"
}
]
}
]
};
function sum(dataObj) {
const hasCmd = dataObj && dataObj.cmd && dataObj.cmd.length > 0;
const hasSales = hasCmd && dataObj.cmd[0].sales && dataObj.cmd[0].sales.length > 0;
if (hasCmd && hasSales) {
const clonedArray = dataObj.cmd[0].sales.slice();
const summedArray = clonedArray.map(function(group) {
const groupKeys = Object.keys(group);
const sum = groupKeys.reduce(function (total, key) {
return total + parseInt(group[key], 10 /* Decimal Radix */);
}, 0);
return Object.assign({}, group, { 'somme': sum.toString() });
});
// build a new object to return to include new summed array
return { "cmd": [{ "sales": summedArray }] };
}
return dataObj;
}
console.log('data', JSON.stringify(data));
const newData = sum(data);
console.log('newData', JSON.stringify(newData));
Maybe you can first and formost refector your tree.
Like that :
{
command: [
{
sales: [
{
quantity: [1, 2, 4],
sum: 7
}
]
}
]
}
I don't know if your structure is open to any refectoring, but you must do something about it !
However, try to use the correct type of value in your row, and try to keep in mind to never mutate and object, use functor like map and reduce :
const cmd = [
{
sales: [
{
quantity: [1, 2, 3],
sum: 0
},
{
quantity: [67, 2, 3],
sum: 0
}
]
}
];
const newObjectWithSum = cmd.map(sales => {
return sales.sales.map((sale) => {
sale.sum = sale.quantity.reduce((valueIn, next) => {
return valueIn + next;
},0);
return sale;
});
})