如何对数组中的对象按name属性分组并累加对应niveau属性值
错误原因
你现有的累加逻辑每次匹配到对应name的对象时,都会先执行this.dataNiveau[this.technos[z].name] = 0将累计值重置为0,再做加法,导致每次累加都是基于0计算,最终只会保留最后一次遍历到的niveau值,无法实现累加效果。
修复方案
方案1:基于原有逻辑修改
先在遍历dataUsers前初始化所有技术的累计值为0,再遍历累加即可:
// 1. 先给所有technos的name初始化累计值为0 for(let z in this.technos){ this.dataNiveau[this.technos[z].name] = 0; } // 2. 遍历dataUsers累加对应name的niveau for(let k in this.dataUsers){ const currName = this.dataUsers[k].name; if(this.dataNiveau.hasOwnProperty(currName)){ this.dataNiveau[currName] += this.dataUsers[k].niveau; } } // 最终得到的dataNiveau为 {java: 4, html: 9}
方案2:更简洁的单循环实现
直接用reduce遍历dataUsers一次即可完成统计,无需提前依赖technos数组初始化:
this.dataNiveau = this.dataUsers.reduce((acc, curr) => { acc[curr.name] = (acc[curr.name] || 0) + curr.niveau; return acc; }, {});
内容的提问来源于stack exchange,提问作者we3z
相关产品推荐
相关产品推荐

