0

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!!!

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
manju k
  • 11
  • 6
  • 1
    Any reason why you use those `{"1": value, "2": value, ...}` objects instead of arrays? – Kelvin Schoofs Jul 21 '21 at 16:59
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Jul 21 '21 at 17:41

2 Answers2

1

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.

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
1

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)
Kinglish
  • 23,358
  • 3
  • 22
  • 43