简体   繁体   English

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

[英]Remove duplicates from an array of objects in JavaScript But merge one field before removing the duplicates

I have the following variable:我有以下变量:

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

So the only difference between the two repeated array of objects is the category ;因此,两个重复的对象数组之间的唯一区别是category where in this example code: 1 is once mentioned with category: ["fruits"] and another time with category: ["vegetables"] .在此示例code: 1曾与category: ["fruits"]一起提及,而另一次与category: ["vegetables"]一起提及。 Now I want to remove the duplicate but before doing so;现在我想删除重复但在这样做之前; I would like to save all the categories of productA into one category: ["fruits", "vegetables"] so the final variable would look like this:我想将productA的所有类别保存到一个category: ["fruits", "vegetables"]所以最终变量如下所示:

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

Here's an example:这是一个例子:

  • Create an object with reduce:使用 reduce 创建一个 object:
    • save each object into the aggregated Object to test if "code" already added将每个 object 保存到聚合的 Object 中以测试“代码”是否已添加
    • if already present then merge the arrays如果已经存在,则合并 arrays
  • transform the object back to an array with Object.values()使用Object.values()将 object 转换回数组

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM