-
狐的传说
var array = [ {key: 'a', value: 2}, {key: 'a', value: 2}, {key: 'a', value: 2}, {key: 'b', value: 8}];var newArr = [{key:array[0].key, value: 0}];array.forEach((item, index)=>{ newArr.forEach((item2, index2) => { if (item.key == item2.key) { newArr[index2].value += item.value; } else { newArr.push(item); } })});console.log(newArr);
-
偶然的你
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]});}
-
胡说叔叔
Array.prototype.reduce 了解一下。array.reduce((resp, obj)=> { var originObj = resp.find(item => item.key === obj.key); if (originObj) { originObj.value+= obj.value; } else { resp.push(obj) } return resp;}, [])
-
开满天机
function keyPlusValue(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(keyPlusValue(arr))
-
喵喔喔
这是我当时解决的方案var arry =[ {name:'a',value:2}, {name:'a',value:2}, {name:'a',value:2}, {name:'b',value:8} ] var temp = {};var data=[]; for(var i in arry) { var key= arry[i].name; if(temp[key]) { temp[key].value = temp[key].value + arry[i].value; temp[key].name = arry[i].name; } else { temp[key] = {}; temp[key].value = arry[i].value; temp[key].name = arry[i].name; } } console.log(temp)
-
Qyouu
var newArr = [...arry.reduce((m, x) => m.set(x.key, (m.get(x.key) || 0) + x.value), new Map())] .map(([key, value]) => ({ key, value }))
-
猛跑小猪
var arry= [ {key:'a',value:2}, {key:'a',value:2}, {key:'a',value:2}, {key:'b',value:8} ] let target = []; let keysArr =[...new Set( arry.map(item=>item.key))] ; keysArr.forEach(item=>{ const arr = arry.filter(keys=>keys.key == item); const sum = arr.reduce((a,b)=>a+b.value,0) target.push({ key:item, value:sum }) }) console.log( target )