Reputation: 11
I have an array of objects that I want to reduce into a single object. The sample array always has the same keys in each of its objects as seen below:
sample = [
{australia: 0, belgium: 0, brazil: 0, canada: 1, china: 1, ...},
{australia: 0, belgium: 0, brazil: 3, canada: 2, china: 2, ...},
{australia: 2, belgium: 1, brazil: 4, canada: 2, china: 5, ...}
]
I am looking to obtain a single object where the keys are the same as in the objects, and the values are a concatenation of each value in the initial array. Something like this:
desiredResult: {australia:[0,0,2],belgium:[0,0,1],brazil:[0,3,4],canada:[1,2,2],china:[1,2,5],...}
So far I have been trying the following reduce method on the array, but I am missing the part where I concatenate all the values:
let desiredResult = sample.reduce((a,b) =>({...a, desiredResult: b}),{})
// Which results in:
// desiredResult: {australia: 2, belgium: 1, brazil: 4, canada: 2, china: 5}
¿Could you help me figure out the best way to reach this solution?
Upvotes: 0
Views: 285
Reputation: 5308
You can try reduce
by taking entries of element in key, value form and then pushing them using for..of
in accumulator
accordingly:
var sample = [{ australia: 0, belgium: 0, brazil: 0, canada: 1, china: 1 }, { australia: 0, belgium: 0, brazil: 3, canada: 2, china: 2 }, { australia: 2, belgium: 1, brazil: 4, canada: 2, china: 5 }]
const result= sample.reduce((acc, elem)=>{
countries= Object.entries(elem);
for(const [country, count] of countries){
acc[country]= acc[country] || [];
acc[country].push(count);
}
return acc;
},{});
console.log(result);
Upvotes: 0
Reputation: 50291
Since each of the lement in the array is again a object , you need to iterate them
let sample = [{
'australia': 0,
'belgium': 0,
'brazil': 0,
'canada': 1,
'china': 1
},
{
'australia': 0,
'belgium': 0,
'brazil': 3,
'canada': 2,
'china': 2
},
{
'australia': 2,
'belgium': 1,
'brazil': 4,
'canada': 2,
'china': 5
}
];
let newData = sample.reduce((acc, curr) => {
for (let keys in curr) {
if (!acc[keys]) {
acc[keys] = []
}
acc[keys].push(curr[keys])
}
return acc;
}, {});
console.log(newData)
Upvotes: 1
Reputation: 386550
You could get the entries and create new properties as array and push the value to it.
var sample = [{ australia: 0, belgium: 0, brazil: 0, canada: 1, china: 1 }, { australia: 0, belgium: 0, brazil: 3, canada: 2, china: 2 }, { australia: 2, belgium: 1, brazil: 4, canada: 2, china: 5 }],
result = sample.reduce((r, o) => {
Object.entries(o).forEach(([k, v]) => (r[k] = r[k] || []).push(v));
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1