2016-01-29 53 views
4

我希望能夠通過增加它們的值一起合併兩個對象合併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; 
} 

任何想法?

回答

3

首先,讓我們來定義應用於一個FUNC兩個對象的組合的抽象函數,然後與求和函數一起使用。

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 = { "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也可以寫在一個更實用的風格,就像這樣:

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)); 
} 

如果你是罰款的第一個對象被改變,你可以跳過clone步驟,只是通過x

0

我嘗試

function MergeRecursive(obj1, obj2) { 
    var k = Object.keys(obj1), i = 0; 
    for (var p in obj2) { 
     if(typeof obj1[p] == 'object' && typeof obj2[p] == 'object') 
      obj2[p] = MergeRecursive(obj1[p],obj2[p]); 
     else if(obj1[p] != null) 
      obj2[p] += obj1[p]; 
     else 
      obj2[k[i]] = obj1[k[i]]; 
     i++; 
    } 
    return obj2; 
} 

使用盡可能

MergeRecursive({ "a" : 1, "b" : 3, "d": {"da": 1}},{ "a" : 1, "c" : 34, "d": {"da": 2} }) 
0

創建resultArray避免與OBJ1的複雜性。然後,只要obj2中的對應鍵存在,只需將obj1中的每個值添加到resultArray中,並將obj2的值累加即可。

然後添加在還沒有通過第一次迭代的resultArray添加obj2的每一個鍵,這樣你就不會從OBJ2丟失數據。

function MergeRecursive(obj1, obj2) { 
     resultArray = []; 
     for (var key in obj1) { 
      if (typeof obj1[key] === 'object') { 
       resultArray[key] = MergeRecursive(obj1[p], obj2[p]); 
      } else { 
       resultArray[key] = obj1[key] + obj2[p] ?? 0; 
      } 
     } 
     for (var key in obj2) { 
      if (key in resultArray){ 
       continue; 
      } 
      resultArray[key] = obj2[key]; 
     } 
     return resultArray; 
    }