2016-04-02 32 views
-2

我有一個數組,其中包含幾乎相同的對象。我想將這些對象合併爲一個,同時保持它們之間不同的數據。如何將兩個幾乎相同的JavaScript對象合併爲一個使用Lodash的對象?

這裏是我的數據:

[ 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 1, name: 'Cat 1'} 
    ] 
    }, 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 2, name: 'Cat 2'} 
    ] 
    } 
] 

我想最後的結果是:

[ 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 1, name: 'Cat 1'}, 
     {id: 2, name: 'Cat 2'} 
    ] 
    } 
] 

任何幫助,將不勝感激!

+0

試用['_.mergeWith()']給出的示例(https://開頭lodash的.com /文檔#mergeWith)。 –

+0

Stackoverflow不是您粘貼數據和所需結果並獲得解決方案的地方。我們在這裏幫助,而不是爲你思考。 – Aristarhys

+0

「幾乎相同」的定義是什麼? –

回答

0
var a1 = [ 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 1, name: 'Cat 1'} 
    ] 
    }, 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 2, name: 'Cat 2'} 
    ] 
    } 
]; 
var a2 = []; 

_.forEach(a1, function(item){ 
    if(a2.length === 0){ 
    a2.push(item); 
    }else{ 
    _.forIn(item, function(value, key){ 
     if(!a2[0].hasOwnProperty(key)){ 
     a2[0][key] = value; 
     }else{ 
      if(typeof value === "object" && value.length > 0){ 
      _.forEach(value, function(v){ 
        console.log("Pushing Item into Categories") 
        a2[0][key].push(v); 
      }) 
      } 
     } 
    }) 
    } 

}) 

console.log(a2) 

這是不是最優雅的解決方案,但它能夠完成任務,並會的「A1」的任何長度數組的項目中合併成1個對象的長度的陣列,並結合任何嵌套數組它迭代。

因此,它可以在下面的陣列上工作以及...只是了一個例子:

var a1 = [ 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 1, name: 'Cat 1'} 
    ], 
    franks: [ 
     {"blaH":"blah"} 
    ] 
    }, 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 2, name: 'Cat 2'} 
    ] , 
    franks: [ 
     {"blaH":"blah1"} 
    ] 
    } , 
    { id: 1, 
    title: 'The title', 
    description: 'The description', 
    categories: [ 
     {id: 2, name: 'Cat 2'} 
    ] , 
    franks: [ 
     {"blaH":"blah2"}, 
     {"blaH":"blah3"} 
    ] 
    } 
]; 
+0

我嘗試了與mergeWith,uniq,union等不同的方式,但沒有得到它。這工作完美。謝謝你的幫助,亞倫。 – kfleisch

相關問題