我希望能夠通過增加它們的值一起合併兩個對象合併2個JavaScript對象。通過遞歸地加入他們的價值觀
> a
{ "a" : 1, "b" : 3, "d": {"da": 1}}
> b
{ "a" : 1, "c" : 34, "d": {"da": 2} }
我想獲得:
> { "a" : 2, "b": 3, "c" : 34, "d": {"da": 3} }
我已經試過,但它不工作:
function MergeRecursive(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its 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 it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
}
任何想法?