JavaScript 数组分组统计:根据 name 属性累加 totalValue
可以使用一个对象来记录各个 name 的 totalValue,然后在 forEach 中判断当前 item 的 name 是否已经在对象中记录过,如果是则累加 totalValue,否则将当前 item 的 name 作为对象的属性,初始值为 0,再累加 totalValue。
示例代码:
var totalValueByNames = {};
arr.forEach(function(item) {
if (totalValueByNames.hasOwnProperty(item.name)) {
totalValueByNames[item.name] += item.value;
} else {
totalValueByNames[item.name] = item.value;
}
item.totalValue = totalValueByNames[item.name];
});
原文地址: https://www.cveoy.top/t/topic/mi8Q 著作权归作者所有。请勿转载和采集!