2016-04-02 38 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

相关问题