4
的阵列的总结我有余额(也有在对象的其他属性,但不导入例如)对象的列表:角2管 - 计算对象
[{ balance : 100 },{ balance : 200 },{ balance : null },{ balance : 300 }]
我找的智能管道,将总结(其他平均值)的余额(不希望使用for循环 - 但一些ES6功能像减少但不知道如何)
的阵列的总结我有余额(也有在对象的其他属性,但不导入例如)对象的列表:角2管 - 计算对象
[{ balance : 100 },{ balance : 200 },{ balance : null },{ balance : 300 }]
我找的智能管道,将总结(其他平均值)的余额(不希望使用for循环 - 但一些ES6功能像减少但不知道如何)
您将需要编写自己的管道,下面应该给你后面的内容。这需要你想总结作为参数
总和
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;
}
您的代码将返回'NaN'。 –
你确定,适合我 –
是的,它现在有效。:) –