I currently have 2 obj and using the jquery extend function, however it's overriding value from keys with the same name. How can I add the values together instead?
var obj1 = {
"orange": 2,
"apple": 1,
"grape": 1
};
var obj2 = {
"orange": 5,
"apple": 1,
"banana": 1
};
mergedObj = $.extend({}, obj1, obj2);
var printObj = typeof JSON != "undefined" ? JSON.stringify : function (obj) {
var arr = [];
$.each(obj, function (key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push(next);
});
return "{ " + arr.join(", ") + " }";
};
console.log('all together: ' + printObj(mergedObj));
And I get obj1 = {"orange":5,"apple":1, "grape":1, "banana":1}
What I need is obj1 = {"orange":7,"apple":2, "grape":1, "banana":1}
All $.extend
does is join the two objects but it doesn't add the values, it overrides them.
You're going to have to do this manually. $.extend
will be useful to add or modify fruits to your object but if you need the total sum you gonna have to loop:
var obj1 = { orange: 2, apple: 1, grape: 1 };
var obj2 = { orange: 5, apple: 1, banana: 1 };
var result = $.extend({}, obj1, obj2);
for (var o in result) {
result[o] = (obj1[o] || 0) + (obj2[o] || 0);
}
console.log(result); //=> { orange: 7, apple: 2, grape: 1, banana: 1 }
Demo: http://jsfiddle.net/elclanrs/emGyb/
Working Demo
That's not how .extend()
works; you'll have to implement your own:
function mergeObjects() {
var mergedObj = arguments[0] || {};
for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];
for (var key in obj) {
if( obj.hasOwnProperty(key) ) {
if( mergedObj[key] ) {
mergedObj[key] += obj[key];
}
else {
mergedObj[key] = obj[key];
}
}
}
}
return mergedObj;
}
Usage:
var obj1 = { "orange": 2, "apple": 1, "grape": 1 };
var obj2 = { "orange": 5, "apple": 1, "banana": 1 };
var mergedObj = mergeObjects( obj1, obj2);
// mergedObj {"orange":7,"apple":2,"grape":1,"banana":1}
Of course, like .extend()
, this will work with any number of objects -- not just 2.
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