从JavaScript中的对象数组中删除重复项,但在删除重复项之前合并一个字段

问题描述 投票:1回答:1

我有以下变量:

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"]...},
    ...
]
javascript arrays duplicates array-merge
1个回答
2
投票

这里是一个例子:

  • 使用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);
© www.soinside.com 2019 - 2024. All rights reserved.