Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  188] [ 1]  / answers: 1 / hits: 22521  / 7 Years ago, mon, february 27, 2017, 12:00:00

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.


More From » sum

 Answers
17

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




[#58757] Friday, February 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
desiraeleandrah

Total Points: 202
Total Questions: 111
Total Answers: 115

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
;