如何计算和显示 javascript 对象的字段总和
How to calculate and display sum of field from javascript 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);
});
尝试制作一个函数来获取总费用金额,它会起作用。
在HTML,
<div *ngFor="let person of data;">
{{person.name}} : Total Expense Amount : {{getTotalExpenseAmount(person)}}
</div>
在ts文件中,添加这个函数,
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>
我有一个对象,我需要在其中显示名称。以及各自的总消费金额。
我可以使用 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);
});
尝试制作一个函数来获取总费用金额,它会起作用。
在HTML,
<div *ngFor="let person of data;">
{{person.name}} : Total Expense Amount : {{getTotalExpenseAmount(person)}}
</div>
在ts文件中,添加这个函数,
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>