I've used this function to merge objects in the past, I use it to add or update existing properties on obj1
with values from obj2
:
var _mergeRecursive = function(obj1, obj2) {
//iterate over all the properties in the object which is being consumed
for (var p in obj2) {
// Property in destination object set; update its value.
if ( obj2.hasOwnProperty(p) && typeof obj1[p] !== "undefined" ) {
_mergeRecursive(obj1[p], obj2[p]);
} else {
//We don't have that level in the heirarchy so add it
obj1[p] = obj2[p];
}
}
}
It will handle multiple levels of hierarchy as well as single level objects. I used it as part of a utility library for manipulating JSON objects. You can find it here.