合并具有相同键值的 JavaScript 对象并对其进行计数
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的对象数组 −
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 } ]