JS对象数组相同属性进行累加,js根据对象数组中某一属性值,合并相同项,并对某一属性累加处理
JS对象数组相同属性进行累加
let info=[
{
name:"小明",
score:100
},{
naem:"小红",
score:110
},
{
name:"小强",
score:120
}
]
let totalScore=info.reduce((pre,cur)=>{
return pre+cur.score
},0)
console.log(totalScore);//输出330
js根据对象数组中某一属性值,合并相同项,并对某一属性累加处理
Example: 根据code合并数组,并将sl值累加,如下两种方法:
let data = [{ code: 1001, name: ‘苹果’, sl: 11 },
{ code: 1001, name: ‘苹果’, sl: 11 },
{ code: 1001, name: ‘苹果’, sl: 11 },
{ code: 1001, name: ‘苹果’, sl: 11 },
{ code: 1002, name: ‘西瓜’, sl: 11 },
{ code: 1002, name: ‘西瓜’, sl: 15 },
{ code: 1003, name: ‘梨’, sl: 15 },
{ code: 1003, name: ‘梨’, sl: 15 }]
第一种:根据对象key的唯一性,累加sl值
let item = {}
for (let i = 0; i < data.length; i++) {
item[data[i].code] = ~~item[data[i].code] + data[i].sl
}
console.log(item)
// 结果: {1001: 44, 1002: 26, 1003: 30}
第二种:根据reduce遍历累加,得到数组
let newArray = data.reduce((total, cur, index) => {
let hasValue = total.findIndex(current => { return current.code === cur.code})
hasValue === -1 && total.push(cur)
hasValue !== -1 && (total[hasValue].sl = total[hasValue].sl + cur.sl)
return total
}, [])
console.log(newArray)
// 结果: [{code: 1001, name: “苹果”, sl: 44}, {code: 1002, name: “西瓜”, sl: 26}, {code: 1003, name: “梨”, sl: 30}]
更多推荐
所有评论(0)