5 回答
TA贡献2039条经验 获得超7个赞
const ary = [{
code: 1,
num: 20
}, {
code: 1,
num: 10
}, {
code: 2,
num: 15
}]
function merge (list) {
let result = []
let cache = {}
list.forEach(item => {
let key = item.code
let index = cache[key]
if (index !== undefined) {
result[index].num += item.num
} else {
result.push(Object.assign({}, item))
cache[key] = result.length - 1
}
})
return result
}
merge(list)
TA贡献1777条经验 获得超3个赞
function merge(arr) {
let res = {};
for(let item of arr) {
if(res[item.code]) res[item.code].num += item.num;
else res[item.code] = { code: item.code, num: item.num }; // Avoid modifying the original object.
}
return Object.values(res);
}
TA贡献1963条经验 获得超6个赞
var abc=[{
code: 1,
num: 20,
}, {
code: 1,
num: 10,
}, {
code: 2,
num: 15,
}]
var result={};
for(i=0;i<abc.length;i++){
if(result[abc[i].code]){
result[abc[i].code]+=abc[i].num;
}else{
result[abc[i].code]=abc[i].num;
}
}
var keyvalue=[];
for(var key in result){
keyvalue.push({code:key,num:result[key]})
}
console.log(keyvalue)
添加回答
举报