我在一个对象数组中有一个数组,我想对嵌套数组中的值求和。
[{BenefitType:'401k',
Beneficiaries: [{Name: 'PersonA', Percentage: 20},
{Name: 'PersonB', Percentage: 30},
{Name: 'PersonC', Percentage: 50}]
},
{BenefitType:'IRA',
Beneficiaries: [{Name: 'PersonA', Percentage: 15},
{Name: 'PersonB', Percentage: 45},
{Name: 'PersonC', Percentage: 40}]
}];
我想根据其福利类型将所有百分比相加,以便401k = 100
和IRA = 100
。
我有以下代码,但它为我提供了百分比的总计,而不是每种福利类型的总计:
var myTotal = 0;
for(var i = 0; i < data.benefit_type.length; i++) {
for(var j=0; j < data.benefit_type[i].beneficiaries.length; j++) {
myTotal += parseInt(data.benefit_type[i].beneficiaries[j].percentage);
data.benefit_type[i].percent_total = myTotal;
}
}
我缺少什么来解决这个问题?
答案 0 :(得分:3)
您可以使用.forEach()
遍历所有对象,.reduce()
对内部数组求和:
let array = [{BenefitType:'401k',
Beneficiaries: [{Name: 'PersonA', Percentage: 20},
{Name: 'PersonB', Percentage: 30},
{Name: 'PersonC', Percentage: 50}]
},
{BenefitType:'IRA',
Beneficiaries: [{Name: 'PersonA', Percentage: 15},
{Name: 'PersonB', Percentage: 45},
{Name: 'PersonC', Percentage: 40}]
}];
array.forEach(x => x.TotalPercentage = x.Beneficiaries.reduce((val, cur) => val + cur.Percentage, 0));
console.log(array);
编辑:
要使用double for循环修复代码,您应该在离开内循环时将myTotal
变量设置为零:
for(var i = 0; i < data.benefit_type.length; i++) {
for(var j=0; j < data.benefit_type[i].Beneficiaries.length; j++) {
myTotal += data.benefit_type[i].Beneficiaries[j].Percentage;
data.benefit_type[i].percent_total = myTotal;
}
myTotal = 0;
}