javascript - 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>
请提供您宝贵的解决方案来解决此问题。感谢你的帮助。谢谢。
解决方案
从我的角度来看,最好的方法是使用 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] }));
}
}
推荐阅读
- node.js - 如何为我的 Heroku 评论应用配置 mLab 插件?
- android - SQLite 多列更新语法错误
- python - 如何使用经过训练的 CNN 获得正确的边界框
- python - 使用 lxml 提取两个 HTML 标题之间的所有文本
- c# - 无法继续使用捕获的 GUI 上下文,但为什么会出现死锁?
- java - maven如何寻找传递依赖
- html - 如何删除第一页页脚中出现的黑色行?
- spring-boot - ZooKeeper 会话在测试中过期
- php - 为什么 base64_encode 函数只在我的一台服务器上引发错误?
- android - google.android.gms:play-services-oss-licenses 在混淆后不起作用