我有以下变量:
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"]...},
...
]
答案 0 :(得分:2)
这是一个例子:
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);