Reputation: 21
I'd like to get the sum of object properties
Here is my Input
{
"Obj1": {
"1": 50,
"2": 45.5,
"3": 15,
"4": 10,
"5": 20
},
"Obj2": {
"1": 12.5,
"2": 0,
"3": 0,
"4": 12.5,
"5": 0
}
}
Want my output to be
Obj1 = 140.5
Obj2 = 25
Let me know if there is a way to get the output as mentioned above in javascript
Thanks in advance!!!
Upvotes: 0
Views: 58
Reputation: 8718
This should work for your use case:
const data = {
"Obj1": { "1": 50, "2": 45.5, "3": 15, "4": 10, "5": 20 },
"Obj2": { "1": 12.5, "2": 0, "3": 0, "4": 12.5, "5": 0 },
};
const sums = {};
for (const key in data) {
sums[key] = Object.values(data[key]).reduce((tot, v) => tot + v, 0);
}
console.log(sums);
// {
// "Obj1": 140.5,
// "Obj2": 25
// }
Mind that with your sequential keys for your sub-objects, it might be better to use arrays.
Upvotes: 1
Reputation: 23664
Here's a method using Object.assign and reduce to create one object with the key/value pairs that correspond with your desired result.
const data = {
"Obj1": { "1": 50, "2": 45.5, "3": 15, "4": 10, "5": 20 },
"Obj2": { "1": 12.5, "2": 0, "3": 0, "4": 12.5, "5": 0 },
};
const result = Object.assign({}, ...Object.entries(data).map(e => ({[e[0]]: Object.entries(e[1]).reduce((b,a) => b+a[1],0)})))
console.log(result)
Upvotes: 1