var obj1 = {
1: { foo: 1 },
2: { bar: 2, fooBar: 3 },
3: { fooBar: 3, boor:{foob: 1, foof: 8} },
4: {continent: {
asia: {country: {india: {capital: "delhi"}, china: {capital: "beiging"}}},
europe:{country:{germany: {capital: "berlin"},france: {capital: "paris"}}}
},
vegtables: {cucumber: 2, carrot: 3, radish: 7}
}
};
var obj2 = {
1: { foo: 1, bar: 2 },
2: { bar: 2 },
3: {fooBar: 3, boor:{foob: 1, boof: 6}, boob: 9 },
4: {continent: {
northamerica: {country: {mexico: {capital: "mexico city"}, canada: {capital: "ottawa"}},},
asia: {country: {Afghanistan : {capital: "Kabul"}}}
}
},
5: {barf: 42}
};
//this function is similar to object.assign but,
//leaves the keys which are common among both bojects untouched
function merge(object1, object2)
{
function combine(p, q)
{
for(i in q)
if(!p.hasOwnProperty(i))
p[i]= q[i];
return p;
}
obj1= Object.assign(combine(obj1, obj2), obj1);//for the first level
obj1= Object.assign(traverse(obj1, obj2), obj1);//for subsequent levels down the object tree
//this function traverses each nested boject and combines it with the other object
function traverse(a, b)
{
if(typeof(a) === "object" && typeof(b) === "object")
for(i in b)
if(typeof(a[i]) === "object" && typeof(b[i]) === "object")
a[i]= Object.assign(traverse(a[i], b[i]), a[i]);
else
Object.assign(combine(a, b), a);
return a;
}
return obj1;
}
console.log(merge(obj1, obj2));