【问题标题】:Angular 2 pipe - calculating summary of array of objectsAngular 2 pipe - 计算对象数组的摘要
【发布时间】:2017-06-29 03:02:57
【问题描述】:

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

[{ balance : 100 },{ balance : 200 },{ balance : null },{ balance : 300 }]

我正在寻找可以对数组中的余额求和(其他平均数)的智能管道(不希望使用 for 循环 - 但一些 ES6 功能,如 reduce,但不确定如何)

【问题讨论】:

    标签: arrays angular sum pipe reduce


    【解决方案1】:

    您将需要编写自己的管道,下面应该会为您提供您所追求的。它将您要求和​​的对象的属性作为参数

    总和

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

    【讨论】:

    • 感谢您提供出色的解决方案。我将其扩展为包含平面数组(没有属性),如下所示: if (attr) { sum = items.reduce((a, b) => a + b[attr], 0); } else { sum = items.reduce((a, b) => a + b, 0); }
    猜你喜欢
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2017-07-30
    • 2018-10-09
    • 2017-08-25
    • 1970-01-01
    相关资源
    最近更新 更多