[英]How to calculate and display sum of field from javascript object
我有一个 object,我需要在其中显示名称。 以及相关人员的总费用金额。
我可以使用ngfor
显示名称。
但是如何显示各个金额的总和。 就像 John 应该显示 50 而 steve 应该显示 170。
谁能帮助我如何做到这一点。
data = [
{
'id' : 1,
'name': john,
'expenselist' = [
{
'expenseid': 1,
'amount' : 20
},
{
'expenseid': 2,
'amount' : 30
},
]
},
{
'id' : 2,
'name': steve,
'expenselist' = [
{
'expenseid': 1,
'amount' : 80
},
{
'expenseid': 2,
'amount' : 90
},
]
}
]
<ion-label *ngFor="let data of data;">
{{data.name}}:
Total Expense Amount:
</ion-label>
我不知道如何使用 ngfor。 但这就是我在普通 JavaScript 中的做法,我希望它能给出一个想法。
data.forEach(person => {
console.log(person.name)
expense_amount = 0
person.expenselist.forEach(expense => {
expense_amout = expense_amount + expense.mount
});
console.log(expense_amount);
});
尝试制作 function 以获得总费用金额,它将起作用。
在 HTML 中,
<div *ngFor="let person of data;">
{{person.name}} : Total Expense Amount : {{getTotalExpenseAmount(person)}}
</div>
在 ts 文件中,添加这个 function,
getTotalExpenseAmount(data) {
return data.expenselist.reduce(
(total, current) => total + current.amount,
0
);
}
使用减少
const mutatedData = data.reduce((acc, value)=>{
acc.push({
name: value.name,
amount: value.expenselist.reduce((acc, value)=>acc+value.amount, 0)
})
}, [])
在 angular 代码中使用 mutatedData 产生结果
<ion-label *ngFor="let data of mutatedData;">
{{data.name}} :
Total Expense Amount : {{data.amount}}
</ion-label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.