Angular 2 Pipe-计算对象数组的摘要 [英] Angular 2 pipe - calculating summary of array of objects

查看:93
本文介绍了Angular 2 Pipe-计算对象数组的摘要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have list of objects with balances (there are other properties in objects but not imported for example):

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

我正在寻找可以对阵列中的余额进行总计(其他平均值)的智能管道(宁愿不使用for循环-而是一些ES6功能,例如reduce但不确定如何使用)

I am looking for smart pipe that would sum (other would average) balances in array (would prefer not using for loop - but some ES6 functionality like reduce but not sure how)

推荐答案

您将需要编写自己的管道,以下内容将为您提供帮助.它以您想要求和的对象的属性作为参数

You will need to write your own pipe, below should give you what you are after. It takes the attribute of the object you want to sum as a parameter

总和

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

使用它就像处理其他任何管道一样

Use it how you would any other pipe

<span>{{ balances | sum:'balances' }}</span>

平均

对于普通管道,只需使用与求和管道类似的逻辑即可.这会将null视为0.

For an average pipe, just use the similar logic as the sum pipe. This treats null as 0.

transform(items: any, attr: string): any {
    let sum = items.reduce((a, b) => a + b[attr], 0);
    return sum / items.length;
}

这篇关于Angular 2 Pipe-计算对象数组的摘要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆