js中一个对象中遇到一个相同的key所对应的value值相加
如图:
变成:
js原生如下:
var abc=[ {typeid:1,ade:1}, {typeid:2,ade:1}, {typeid:1,ade:2}, {typeid:1,ade:2}, {typeid:2,ade:2}, ] var result={}; for(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)
es6如下:
var arry= [ {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] += item.value; }else{ result[item.key] = item.value; } }) let s = []; for(let k in result){ s.push({key:k,value:result[k]}); }