合并具有相同键值并计数的 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 } ]
广告