在 angularjs 中执行 Group By 和 Sum by 属性 [英] Perform Group By and Sum by property in angularjs

查看:27
本文介绍了在 angularjs 中执行 Group By 和 Sum by 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以有一个简单的页面,使用 ng-repeat="(key, value) in data| groupBy: 'Id'"我想对数据进行分组通过已知属性,并对其中一个字段执行聚合求和.我使用了 angular-filter.js 库,利用 groupBy 过滤器来促进这一点.现在的问题是我还想执行汇总总和,并且每个组只显示一行.所以说我有一个对象数组,

`[{Id:1,name:"harry",volume:500},{Id:1,name:"harry",volume:200},{Id:2,name:"Fred",volume:150},{Id:2,name:"Fred",volume:500},{Id:3,name:"Sally",volume:450},{Id:3,name:"Sally",volume:100}]`

如上所示,唯一 ID 的卷是不同的.我想在按 id 分组并汇总卷(总和)后返回以下内容.

`[{Id:1,name:"harry",volume:700},{Id:1,name:"Fred",volume:650},{Id:1,name:"Sally",volume:550}]`

编辑我想根据情况在 2 个显示之间切换,即(所有行)和(分组行).我已经通过使用带有复选框标志的 ng-show 来确定要显示哪个视图来实现这一点.我想这样做而不必像我在这里所做的那样编写额外的标记MyPlunkr 样本
这种方式是我的首选方式,但需要在不写太多额外标记的情况下执行此操作.也许自定义过滤器就足够了?

解决方案

您在每次迭代中都有分组的对象,因此很容易找到总和:

$scope.getVolumeSum = function(items) {退换货品.map(function(x) { return x.volume; }).reduce(function(a, b) { return a + b; });};

id: {{ key }}, name: {{ items[0].name }}, volume: {{ getVolumeSum(items) }}

JSFIDDLE 示例

Ok so have a simple page that displays a collection of objects in using ng-repeat="(key, value) in data| groupBy: 'Id'"I would like to group the data by a known property and also perform aggregate sum on one of the fields. I've used the angular-filter.js library leveraging the groupBy filter to facilitate this. The issue now is that I would like to also perform the aggregate sum and also display only a single row for each group. so say I have an array of objects,

`[{Id:1,name:"harry",volume:500},
{Id:1,name:"harry",volume:200},
{Id:2,name:"Fred",volume:150},
{Id:2,name:"Fred",volume:500},
{Id:3,name:"Sally",volume:450},
{Id:3,name:"Sally",volume:100}
]`

As shown above, the volumes are different for unique id's. I'd like to return this below after grouping by id and aggregating volumes(sum).

`[{Id:1,name:"harry",volume:700},
{Id:1,name:"Fred",volume:650},
{Id:1,name:"Sally",volume:550}
]`

EDIT I'd like to toggle between 2 displays i.e (all rows) and (grouped rows) as the case may be. I've implemented this by using ng-show with a checkbox flag to determine which view to display.I'd like to do this without having to write extra mark up as i've done here MyPlunkr SAMPLE
This way is my preferred way but there is a requirement to do this without writing to much extra mark up. Perhaps a custom filter would suffice ?

解决方案

You have the grouped objects on each iteration, so finding the sum is very easy:

$scope.getVolumeSum = function(items) {
    return items
        .map(function(x) { return x.volume; })
        .reduce(function(a, b) { return a + b; });
};

and

<div ng-repeat="(key, items) in data | groupBy: 'Id'">
  id: {{ key }}, name: {{ items[0].name }}, volume: {{ getVolumeSum(items) }}
</div>

JSFIDDLE SAMPLE

这篇关于在 angularjs 中执行 Group By 和 Sum by 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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