How to $.extend 2 objects by adding numerical values together from keys with the same name?

Posted by muudless on Stack Overflow See other posts from Stack Overflow or by muudless
Published on 2012-08-31T03:11:44Z Indexed on 2012/08/31 3:38 UTC
Read the original article Hit count: 122

Filed under:
|

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?

obj1 = {"orange":2,"apple":1, "grape":1} 
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}

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery