[英]How to calculate and display sum of field from javascript object
I have an object, where I need to display name.我有一个 object,我需要在其中显示名称。 and the total expense amount of respective person.
以及相关人员的总费用金额。
I am able to display name by using ngfor
.我可以使用
ngfor
显示名称。
But how to display the sum of respective amount.但是如何显示各个金额的总和。 Like for John it should display 50 and for steve it should display 170.
就像 John 应该显示 50 而 steve 应该显示 170。
Can anyone please help me how to do this.谁能帮助我如何做到这一点。
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>
I don't know how to use ngfor.我不知道如何使用 ngfor。 but this is how I would do it in normal JavaScript, I hope it will give an idea.
但这就是我在普通 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);
});
Try to make a function to get Total expense amount and it will work.尝试制作 function 以获得总费用金额,它将起作用。
In HTML,在 HTML 中,
<div *ngFor="let person of data;">
{{person.name}} : Total Expense Amount : {{getTotalExpenseAmount(person)}}
</div>
In ts file, add this function,在 ts 文件中,添加这个 function,
getTotalExpenseAmount(data) {
return data.expenselist.reduce(
(total, current) => total + current.amount,
0
);
}
use reduce使用减少
const mutatedData = data.reduce((acc, value)=>{
acc.push({
name: value.name,
amount: value.expenselist.reduce((acc, value)=>acc+value.amount, 0)
})
}, [])
the use mutatedData inside your angular code to produce result在 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.