从 JavaScript 中的一组对象中删除重复项,但在删除重复项之前合并一个字段
Remove duplicates from an array of objects in JavaScript But merge one field before removing the duplicates
我有以下变量:
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"]...},
...
]
这是一个例子:
- 使用 reduce 创建一个对象:
- 将每个对象保存到聚合对象中以测试是否"code"已经添加
- 如果已经存在则合并数组
- 使用
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);
我有以下变量:
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"]...},
...
]
这是一个例子:
- 使用 reduce 创建一个对象:
- 将每个对象保存到聚合对象中以测试是否"code"已经添加
- 如果已经存在则合并数组
- 使用
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);