Lionel B
Lionel B

Reputation: 1174

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.

Upvotes: 20

Views: 26313

Answers (5)

Andrew Parks
Andrew Parks

Reputation: 8087

If you have just two objects:

const x = { a: 12, b: 8, c: 17 }
const y = { a: 2,  b: 4, c: 1 }

const z = Object.fromEntries(Object.keys(x).map(k=>[k,x[k]+y[k]])) 

console.log(z)

or, if you have many objects:

const arr = [{ a: 33, b: 44, c: 55 }, { a: 12, b: 8, c: 17 }, { a: 2,  b: 4, c: 1 }]

const z = Object.fromEntries(Object.keys(arr[0]).map(k=>[k,arr.reduce((s,o)=>s+o[k],0)]))

console.log(z)

Upvotes: 0

baao
baao

Reputation: 73211

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

Upvotes: 36

Carlos Rufo
Carlos Rufo

Reputation: 446

A little bit deeper, all you want as long as objects are equivalent!

const arr = [{
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  },
  {
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  },
  {
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  }
];

const deepMergeSum = (obj1, obj2) => {
  return Object.keys(obj1).reduce((acc, key) => {
    if (typeof obj2[key] === 'object') {
      acc[key] = deepMergeSum(obj1[key], obj2[key]);
    } else if (obj2.hasOwnProperty(key) && !isNaN(parseFloat(obj2[key]))) {
      acc[key] = obj1[key] + obj2[key]
    }
    return acc;
  }, {});
};

const result = arr.reduce((acc, obj) => acc = deepMergeSum(acc, obj));
console.log('result: ', result);

Upvotes: 15

Nina Scholz
Nina Scholz

Reputation: 386519

If the objects have all common keys, you could take the keys from one object in advance and iterate for creating a new result object and later the keys from the single objects.

var o1 = { a: 12, b: 8, c: 17 },
    o2 = { a: 2, b: 4, c: 1 },
    keys = Object.keys(o1),
    result = [o1, o2].reduce(function (r, o) {
        keys.forEach(function (k) {
            r[k] += o[k];
        });
        return r;
    }, keys.reduce(function (r, k) {
        r[k] = 0;
        return r;
    }, Object.create(null)));
    
console.log(result);

Upvotes: 0

Tumen_t
Tumen_t

Reputation: 801

Try this.

let t1 = 
{ 
  a:12,
  b:8,
  c:17
};

let t2 = 
{ 
  a:2,
  b:4,
  c:1
};

function sum(ob1, ob2) {
  let sum = {};

  Object.keys(ob1).forEach(key => {
    if (ob2.hasOwnProperty(key)) {
      sum[key] = ob1[key] + ob2[key]
    }  
  })
  return sum;
}

sum(t1, t2);

https://jsfiddle.net/fbnt2vhe/

Upvotes: 2

Related Questions