合并具有相同键值的JavaScript对象并计数
假设我们有一个像这样的对象数组-
const arr = [{"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 10,
"id": "111",
"name":
"BlackCat",
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
}];
我们需要编写一个包含一个这样的数组的JavaScript函数。
然后,该函数应将所有具有“ id”属性的公共值的对象合并在一起。
因此,对于上述数组,输出应类似于-
const output = [{"value": 10,
"id": "111",
"name": "BlackCat",
"count": 2,
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
"count": 1,
}]
示例
const arr = [{"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
}];
const combinedItems = (arr = []) => {
const res = arr.reduce((acc, obj) => {
let found = false;
for (let i = 0; i < acc.length; i++) {
if (acc[i].id === obj.id) {
found = true;
acc[i].count++;
};
}
if (!found) {
obj.count = 1;
acc.push(obj);
}
return acc;
}, []);
return res;
}
console.log(combinedItems(arr));
输出结果
控制台中的输出将是-
[{ value: 10, id: '111', name: 'BlackCat', count: 2 },
{ value: 15, id: '777', name: 'WhiteCat', count: 1 }
]
以上是 合并具有相同键值的JavaScript对象并计数 的全部内容, 来源链接: utcz.com/z/350147.html