[英]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:这是一个例子:
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.