后端返回的数据,前端需要根据对象里的某个属性合并相同的属性
方法一:
let array = [
{ key: "a", value: "2" },
{ key: "a", value: "2" },
{ key: "a", value: "2" },
{ key: "b", value: "8" }
];
let result = {};
array.forEach((item) => {
if (result[item.key]) {
result[item.key] += Number(item.value);
} else {
result[item.key] = Number(item.value);
}
});
let s = [];
for (let k in result) {
s.push({ key: k, value: result[k] });
}
console.log(s);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
****方法二:****
- 1
let abc=[ {typeid:"韩元",ade:1}, {typeid:"人民币",ade:10000}, {typeid:"人民币",ade:200000}, {typeid:"美元",ade:200}, {typeid:"美元",ade:200}, ] let result={}; for(let i=0;i<abc.length;i++){ if(result[abc[i].typeid]){ result[abc[i].typeid]+=abc[i].ade; }else{ result[abc[i].typeid]=abc[i].ade; } } console.log(result) var keyvalue=[]; for(var key in result){ keyvalue.push({typeid:key,adelenth:result[key]}) } console.log(keyvalue)
转自于:https://blog.csdn.net/weixin_48645836/article/details/106756056?utm_medium=distribute.pc_relevant.none-task-blog-utm_term-2&spm=1001.2101.3001.4242