merge 2 javascript objects by recursively adding their values -


i want able merge 2 objects adding values together.

> { "a" : 1, "b" : 3, "d": {"da": 1}} > b { "a" : 1, "c" : 34, "d": {"da": 2} } 

i want obtain :

> { "a" : 2, "b": 3, "c" : 34, "d": {"da": 3} } 

i've tried doesn't work :

 function mergerecursive(obj1, obj2) {    (var p in obj2) {      try {        // property in destination object set; update value.        if ( obj2[p].constructor==object ) {          obj1[p] += mergerecursive(obj1[p], obj2[p]);         } else {              obj1[p] = obj2[p];        }       } catch(e) {        // property in destination object not set; create , set value.              obj1[p] = obj2[p];      }    }    return obj1;  } 

any ideas ?

first, let's define abstract function applies func combination of 2 objects, , use summation function.

function merge(x, y, fn) {      var result = {};        object.keys(x).foreach(function(k) {          result[k] = x[k];      });        object.keys(y).foreach(function(k) {          result[k] = k in x ? fn(x[k], y[k]) : y[k];      });        return result;  }    function add(p, q) {      if(typeof p === 'object' && typeof q === 'object') {          return merge(p, q, add);      }      return p + q;  }    = { "a" : 1, "b" : 3, "d": {"da": 1}};  b = { "a" : 1, "c" : 34, "d": {"da": 2}};    sum = merge(a, b, add)  document.write('<pre>'+json.stringify(sum,0,3));

merge can written in more functional style, this:

function clone(x) {     return object.keys(x).reduce(function(res, k) {         res[k] = x[k];         return res;     }, {}); }  function merge(x, y, fn) {     return object.keys(y).reduce(function(res, k) {         res[k] = k in x ? fn(x[k], y[k]) : y[k];         return res;     }, clone(x)); } 

if you're fine first object being changed, can skip clone step , pass x.


Comments