Skip to content Skip to sidebar Skip to footer

Javascript/coffeescript Sum Objects

I would love to 'add/merge' (not sure how to call that) some objects in this manner: obj1 = { a: 1, b: 1, c: 1 } obj2 = { a: 1, b: 1 } obj1 + obj2 => { a: 2, b: 2,

Solution 1:

There isn't a built-in way to do it but you can enumerate the properties of one object and add their values to another.

const a = { a: 1, b: 1, c: 1 };
const b = { a: 1, b: 1 };
for(const prop in b) {
  a[prop] = (prop in a ? a[prop] : 0) + b[prop];
}
console.log(a);

The prop in a check is so that we don't end up with NaN by adding undefined to the value in b.

You could use reduce to combine n number of objects like so:

const a = { a: 1, b: 1, c: 1 };
const b = { a: 1, b: 1 };
const c = { a: 1, c: 1 };
const result = [a, b, c].reduce((p, c) => {
  for(const prop in c) {
    p[prop] = (prop in p ? p[prop] : 0) + c[prop];
  }
  return p;
}, {});
console.log(result);

You didn't mention how you wanted to deal with properties in the prototype chain. You should know that for...in will enumerate properties in the prototype chain and prop in x will also examine the prototype chain. If your only want to enumerate the objects own properties then you could use Object.entries() to get its own properties or do a hasOwnProperty(...) check within the for...in and in place of the prop in x check. If you don't do any prototypal inheritance with your models then you may not care.

Solution 2:

A quick answer:

let sum = {};
let keys = newSet(Object.keys(obj1))
Object.keys(obj2).map(x => keys = keys.add(x))

keys.forEach(x => {
	let op1 = obj1[x] || 0;
	let op2 = obj2[x] || 0;
	sum[x] = op1 + op2;
})

Solution 3:

Create an empty object:

var obj3 = {};

Use the spread operator to grab all the keys from both objects, then add them to the new object like so:

for(var i in {...obj1, ...obj2}) {
  obj3[i] = (obj1[i] || 0) + (obj2[i] || 0);
}

var obj1 = { 
  a: 1,
  b: 1,
  c: 1
}

var obj2 = { 
  a: 1,
  b: 2,
  d: 3
}

var obj3 = {};

for(var i in {...obj1, ...obj2}) {
  obj3[i] = (obj1[i] || 0) + (obj2[i] || 0);
}

console.log(obj3);

Post a Comment for "Javascript/coffeescript Sum Objects"