我有带有余额的对象列表(例如,对象中还有其他属性但未导入):
[{ balance : 100 },{ balance : 200 },{ balance : null },{ balance : 300 }]
我正在寻找可以对数组中的余额求和(其他会取平均值)的智能管道(不希望使用 for 循环 - 但一些 ES6 功能,如 reduce 但不确定如何使用)
最佳答案
您需要编写自己的管道,下面应该会给出您想要的内容。它以你想要求和的对象的属性作为参数
求和
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sum'
})
export class SumPipe implements PipeTransform {
transform(items: any[], attr: string): any {
return items.reduce((a, b) => a + b[attr], 0);
}
}
像使用其他管道一样使用它
<span>{{ balances | sum:'balances' }}</span>
平均
对于平均管道,只需使用与求和管道类似的逻辑。这会将 null
视为 0。
transform(items: any, attr: string): any {
let sum = items.reduce((a, b) => a + b[attr], 0);
return sum / items.length;
}
关于arrays - Angular 2 pipe - 计算对象数组的摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164896/