I\'m stuck how i sum two object like this:
obj1 = {
\'over_due_data\': 10,
\'text_data\': 5
}
obj2 = {
\'over_due_data\': 20,
\'text_data\': 5
}
<
I have used below snippet to sum the two objects even if any of them has additional properties.
This solution is based on Array.prototype.reduce and short-circuit evaluation
Object.keys({ ...obj1, ...obj2 }).reduce((accumulator, currentValue) => {
accumulator[currentValue] =
(obj1[currentValue] || 0) + (obj2[currentValue] || 0);
return accumulator;
}, {});
var obj1 = {
'over_due_data': 10,
'text_data': 5,
'some_add_prop': 80
};
var obj2 = {
'over_due_data': 20,
'text_data': 5,
'add_prop': 100
};
const sumOfObjs = Object.keys({ ...obj1,
...obj2
}).reduce((accumulator, currentValue) => {
accumulator[currentValue] =
(obj1[currentValue] || 0) + (obj2[currentValue] || 0);
return accumulator;
}, {});
console.log(sumOfObjs);