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

时间:2020-04-27 22:12:57

标签: javascript arrays duplicates array-merge

我有以下变量:

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"]...},
    ...
]

1 个答案:

答案 0 :(得分: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);

相关问题