I have two different objects
var objA = { a: 10, b: 20, c: 30 }; var objB = { a: 3, c: 6, d: 3 };
and I want to sum their values , like in this example below
{ a: 13, b: 20, c: 36, d: 3 }
Use Array#reduce
method
var objA = {
a: 10,
b: 20,
c: 30
};
var objB = {
a: 3,
c: 6,
d: 3
};
console.log(
// concatenate keys array
Object.keys(objA).concat(Object.keys(objB))
// or use Object.keys(Object.assign({},objA,objB))
// iterate to generate the object
.reduce(function(obj, k) {
// define object property, treat as 0 if not defined
obj[k] = (objA[k] || 0) + (objB[k] || 0);
// return object difference
return obj;
// set initial value as an empty object
}, {})
)
Or much better way by defining initial value as the copy of second object.
var objA = {
a: 10,
b: 20,
c: 30
};
var objB = {
a: 3,
c: 6,
d: 3
};
console.log(
// get property names array of objB ----Edit objA -----
Object.keys(objA)
// iterate over array
.reduce(function(obj, k) {
// add value to existing property or update
obj[k] = (obj[k] || 0) + objA[k];
// return object reference
return obj;
// define initial value as an object which holds
// all the property and value in objB
}, Object.assign({}, objB))
)
Using lodash
function customizer(objValue, srcValue) {
if(objValue && srcValue)
return objValue+srcValue;
}
var objA = { a: 10, b: 20, c: 30 }; var objB = { a: 3, c: 6, d: 3 };
console.log(_.mergeWith(objA, objB, customizer));
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With