8 回答
TA贡献1804条经验 获得超3个赞
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);
TA贡献1841条经验 获得超3个赞
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]});
}
TA贡献1804条经验 获得超8个赞
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;
}, [])
TA贡献1786条经验 获得超13个赞
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))
TA贡献1735条经验 获得超5个赞
这是我当时解决的方案
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)
TA贡献1786条经验 获得超11个赞
var newArr = [...arry.reduce((m, x) => m.set(x.key, (m.get(x.key) || 0) + x.value), new Map())]
.map(([key, value]) => ({ key, value }))
TA贡献1858条经验 获得超8个赞
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 )
添加回答
举报