【问题标题】:How can I merge two almost identical javascript objects into one using Lodash?如何使用 Lodash 将两个几乎相同的 javascript 对象合并为一个?
【发布时间】:2016-04-02 13:29:31
【问题描述】:

我有一个数组,其中包含许多几乎相同的对象。我想将这些对象合并为一个,同时保持它们之间不一样的数据。

这是我的数据:

[
  { 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'} 
    ] 
  } 
]

任何帮助将不胜感激!

【问题讨论】:

  • 试试_.mergeWith()的例子。
  • Stackoverflow 不是您粘贴数据和所需结果并获得解决方案的地方。我们在这里为您提供帮助,而不是为您考虑。
  • “几乎相同”的定义是什么?
  • 到目前为止,我已经尝试过 _.uniq、_uniqWith、_.union、_.unionWith 以及它们的组合。谢谢你,Aristarhys 的有用评论。随着我更多地使用 Stackflow,我希望我有机会回报这个人情。
  • 谢谢你,乔纳森!我认为这对我有用。感谢您的帮助。

标签: javascript arrays node.js lodash


【解决方案1】:
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"}
    ]
  } 
];

【讨论】:

  • 我用 mergeWith、uniq、union 等尝试了不同的方法,但没有得到它。这非常有效。谢谢你的帮助,亚伦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2020-05-16
  • 2013-05-27
  • 1970-01-01
  • 2015-06-03
相关资源
最近更新 更多