首页 > 解决方案 > Angular 4中的多列分组

问题描述

我正在尝试按角度 4 中的数组进行分组。我正在使用自定义管道方法按数组进行分组,如下所示:

https://www.competa.com/blog/custom-groupby-pipe-angular-4/

但我试图按多列分组。

数据

var myArray = [
    {
        name: "Apple",
        color: "Green",
        grade: "A1"
    },
    {
        name: "Apple",
        color: "Red",
        grade: "A1"
    },
    {
        name: "Apple",
        color: "Green",
        grade: "A2"
    },
    {
        name: "Apple",
        color: "Red",
        grade: "A2"
    },
];

在这里,我想按多个列分组,例如名称和等级。

我试过在没有帮助的情况下这样使用:

<li *ngFor="let object of myArray | groupBy:'name,grade'"></li>

请提供您宝贵的解决方案来解决此问题。感谢你的帮助。谢谢。

标签: javascriptjqueryangulartypescript

解决方案


从我的角度来看,最好的方法是使用 lodash。

HTML:-

<ul>
    <li *ngFor="let object of myArray | groupBy:['color','name']"></li>
</ul>

管道:-

import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash';

@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
    transform(collection: Array, property: Array): Array {

        if(!collection) {
            return null;
        }
        var notNull = _.negate(_.isNull);
        const groupedCollection = _.groupBy(collection, function(note){
                          return _.find(_.pick(note, property), notNull);
        });
        return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
    }
}

推荐阅读