var arry= [
{key:'a',value:2},
{key:'a',value:2},
{key:'a',value:2},
{key:'b',value:8}
]
function mergeObject(arr) {
const result = arr.reduce((obj, item) => {
if (!obj[item.key]) {
obj[item.key] = 0
}
obj[item.key] += item.value
return obj
}, {})
return Object.keys(result).map(key => ({key: key, value: result[key]}))
}
console.log(mergeObject(arr))
合并数组中相同key值,对应的value值相加
最新推荐文章于 2023-09-04 11:30:49 发布