【问题标题】:Remove duplicates from an array of objects in JavaScript But merge one field before removing the duplicates从 JavaScript 中的一组对象中删除重复项但在删除重复项之前合并一个字段
【发布时间】:2020-08-11 15:00:32
【问题描述】:

我有以下变量:

var allProducts = [
    {"code": 1,"name": "productA", "category": ["fruits"],...},
    {"code": 1,"name": "productA", "category": ["vegetables"],...},
    {"code": 2,"name": "productB", "category": ["meat"],...},
    ...
]

所以两个重复的对象数组之间的唯一区别是category;在此示例中,code: 1 一次与 category: ["fruits"] 一起提及,另一次与 category: ["vegetables"] 一起提及。现在我想删除重复但在这样做之前;我想将productA 的所有类别保存到一个category: ["fruits", "vegetables"] 中,因此最终变量将如下所示:

var allProductsCleaned = [ 
    {"code": 1,"name": "productA", "category": ["fruits", "vegetables"],...},
    {"code": 2,"name": "productB", "category": ["meat"]...},
    ...
]

【问题讨论】:

  • 我认为你在变量中输入了错误的objectkey。应该是这样的? var allProducts = [ {"code": 1,"name": "productA", "category": ["fruits"],...},...
  • 这能回答你的问题吗? merging duplicates in javascript array
  • 已编辑问题,因为对象的格式不正确。

标签: javascript arrays duplicates array-merge


【解决方案1】:

这是一个例子:

  • 使用 reduce 创建一个对象:
    • 将每个对象保存到聚合对象中以测试是否已添加“代码”
    • 如果已经存在则合并数组
  • Object.values()将对象转换回数组

const allProducts = [
    {"code": 1,"name": "productA", "category": ["fruits"]},
    {"code": 1,"name": "productA", "category": ["vegetables"]},
    {"code": 2,"name": "productB", "category": ["meat"]},
    {"code": 2,"name": "productB", "category": ["fish"]},
    {"code": 2,"name": "productB", "category": ["fish"]}
]

const output = Object.values(allProducts.reduce((aggObj, item) => {  
  if (aggObj[item.code]){
    //item already exists so merge the category arrays:
    const newArr = [...new Set([...aggObj[item.code].category, ...item.category])]
    aggObj[item.code].category = newArr;
  }else{
    //doesn't already exist:
    aggObj[item.code] = item;
  }  
  return aggObj
}, {}));

console.log(output);

【讨论】:

  • 完美!这正是我一直在寻找的。谢谢亚历克斯!快速询问此处代码为 1 的产品;与["fruits"] 具有相同的类别;使用上面的代码,它将合并它并将类别输出为` ["fruits", "fruits" ]. Right? How can I prevent that when if the category array` 包含单词fruit 以不合并它们?
  • 太好了,请参阅我更新的答案 - 我们可以使用 ES6 new Set([iterable]) 来确保唯一的条目(还有其他方法可以做到这一点,例如使用 arr.inlcudes(item))。如果我的回答解决了您的问题,请考虑标记为已接受的答案并投票:)
  • 你太棒了!赞成并接受作为答案!谢谢
猜你喜欢
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 2020-04-02
  • 2017-04-10
  • 1970-01-01
  • 2022-01-24
相关资源
最近更新 更多