Search code examples
javascriptsum

How can I sum properties from two objects?


I have multiple JavaScript objects:

{
  a: 12,
  b: 8,
  c: 17
}

and

{
  a: 2,
  b: 4,
  c: 1
}

I need to sum these two object by keys

Result:

{
  a: 14,
  b: 12,
  c: 18
}

Do you have any solutions in JavaScript? I use Object.keys.map but it's too long because I have like 100 elements in my object.


Solution

  • You can use reduce for that, below function takes as many objects as you want and sums them by key:

    var obj1 = {
      a: 12,
      b: 8,
      c: 17
    };
    
    var obj2 = {
      a: 12,
      b: 8,
      c: 17
    };
    
    var obj3 = {
      a: 12,
      b: 8,
      c: 17
    };
    
    
    function sumObjectsByKey(...objs) {
      return objs.reduce((a, b) => {
        for (let k in b) {
          if (b.hasOwnProperty(k))
            a[k] = (a[k] || 0) + b[k];
        }
        return a;
      }, {});
    }
    
    console.log(sumObjectsByKey(obj1, obj2, obj3));