'Javascript: How to merge two objects and sum the values of the same key?
const map1 = { "a": 10, "b": 6 };
const map2 = { "a": 10, "b": 6, "c": 7, "d": 8 };
I want to merge them and sum their values
if they have the same key
:
const result = { "a": 20, "b": 12, "c": 7, "d": 8 };
How can you achieve this without using any external library or ++
? Thanks!
Solution 1:[1]
Using Array#reduce
and Object#entries
:
const
map1 = { "a": 10, "b": 6 },
map2 = { "a": 10, "b": 6, "c": 7, "d": 8 };
// iterate over map2 entries with acc set to map1 at start
const merged = Object.entries(map2).reduce((acc, [key, value]) =>
// if key is already in map1, add the values, otherwise, create new pair
({ ...acc, [key]: (acc[key] || 0) + value })
, { ...map1 });
console.log(merged);
Solution 2:[2]
I came up with this code, more readable and simpler though longer version const map1 = { "a": 10, "b": 6 , x: 22}; const map2 = { "a": 10, "b": 6, "c": 7, "d": 8 };
function addMerge(obj1, obj2){
let res = {}
let A = Object.keys(obj1)
let B = Object.keys(obj2)
if(A.length > B.length){
Object.keys(obj1).forEach((k, i) => {
if(obj2.hasOwnProperty(k))
res[k] = obj2[k] + obj1[k]
else
if(B[i] !== undefined){
res[k] = obj1[k]
res[B[i]] = obj2[B[i]]
}
else
res[k] = obj1[k]
});
}
else{
Object.keys(obj2).forEach((k, i) => {
if(obj1.hasOwnProperty(k))
res[k] = obj2[k] + obj1[k]
else
if(A[i] !== undefined){
res[k] = obj2[k]
res[A[i]] = obj1[A[i]]
}
else
res[k] = obj2[k]
});
}
console.log("Result", res)
}
addMerge(map1, map2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Majed Badawi |
Solution 2 | optimus |