如何使用 Lodash 将两个几乎相同的 javascript 对象合并为一个对象?

How can I merge two almost identical javascript objects into one using 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'} 
    ] 
  } 
]

如有任何帮助,我们将不胜感激!

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"}
    ]
  } 
];