有没有办法对 Angular 中的对象字段进行分组?
Is there a way to group object fields in Angular?
我相信我正在寻找一个 Angular 管道,它允许我根据数组中定义的键将数组中的项目分组在一起。例如,如果我有一个包含这些 state
和国家 keys
:
的数组
items: any = [
{
"state": "Illinois",
"country": "USA"
},
{
"state": "Florida",
"country": "USA"
},
{
"state": "Ontario",
"country": "Canada"
}
];
当我遍历我的列表时,我希望管道将具有相同键的项目组合在一个列表中,这样当它显示给用户时,他们可以一起看到相似的项目。
我是否需要为此创建自定义管道或仅以特定方式过滤项目,或者有没有办法使用 rxjs
中的 map
或 [=16] 来完成此操作=]?
我不确定这个 post 没有遵循哪些准则,但这是我经过多次尝试后的解决方案:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'groupBy'
})
export class GroupByPipe implements PipeTransform {
transform(collection: any[], property: string): any[] {
// prevents the application from breaking if the array of objects doesn't exist yet
if(!collection) {
return null;
}
const groupedCollection = collection.reduce((previous, current) => {
if (!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
// this will return an array of objects, each object containing a group of objects
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
现在它是我的模板,我可以使用管道将项目组合在一起:
<div *ngFor="let category of categories | groupBy: 'category'">
<h3>{{ category.key }}</h3>
<ul>
<li *ngFor="let item of category.value">{{ item.title }}</li>
</ul>
</div>
我相信我正在寻找一个 Angular 管道,它允许我根据数组中定义的键将数组中的项目分组在一起。例如,如果我有一个包含这些 state
和国家 keys
:
items: any = [
{
"state": "Illinois",
"country": "USA"
},
{
"state": "Florida",
"country": "USA"
},
{
"state": "Ontario",
"country": "Canada"
}
];
当我遍历我的列表时,我希望管道将具有相同键的项目组合在一个列表中,这样当它显示给用户时,他们可以一起看到相似的项目。
我是否需要为此创建自定义管道或仅以特定方式过滤项目,或者有没有办法使用 rxjs
中的 map
或 [=16] 来完成此操作=]?
我不确定这个 post 没有遵循哪些准则,但这是我经过多次尝试后的解决方案:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'groupBy'
})
export class GroupByPipe implements PipeTransform {
transform(collection: any[], property: string): any[] {
// prevents the application from breaking if the array of objects doesn't exist yet
if(!collection) {
return null;
}
const groupedCollection = collection.reduce((previous, current) => {
if (!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
// this will return an array of objects, each object containing a group of objects
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
现在它是我的模板,我可以使用管道将项目组合在一起:
<div *ngFor="let category of categories | groupBy: 'category'">
<h3>{{ category.key }}</h3>
<ul>
<li *ngFor="let item of category.value">{{ item.title }}</li>
</ul>
</div>