Angular 2 pipe - 计算对象数组的摘要

Angular 2 pipe - calculating summary of array of objects

我有带有余额的对象列表(例如,对象中还有其他属性但未导入):

[{ 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;
}