How can I sum properties from two objects?

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));

Leave a Comment