我的Angular2应用上有一组数组,用于在我的视图中使用*ngFor
构建分组列表:
[
{
category: 1,
items: [{ id: 1, name: "helloworld1" }, { id: 2, name: "helloworld2" }]
},
{
category: 2,
items: [{ id: 3, name: "helloworld3" }, { id: 4 }]
},
{
category: 3,
items:[{ id: 5 }, { id: 6 }]
}
]
我还有一个布尔值,当它为true时应该只过滤具有name
属性的项目。如果一个组没有任何符合此条件的项目,则不应通过。因此,如果布尔值为真,结果如下:
[
{
category: 1,
items: [{ id: 1, name: "helloworld1" }, { id: 2, name: "helloworld2" }]
},
{
category: 2,
items: [{ id: 3, name: "helloworld3" }]
}
]
如何实现管道来实现这种结果?
答案 0 :(得分:1)
http://plnkr.co/edit/je2RioK9pfKxiZg7ljVg?p=preview
@Pipe({name: 'filterName'})
export class FilterNamePipe implements PipeTransform {
transform(items: any[], checkName: boolean): number {
if(items === null) return [];
let ret = [];
items.forEach(function (item) {
let ret1 = item.items.filter(function (e) {
return !checkName || (checkName && (e.name !== undefined));
});
if(ret1.length > 0) {
item.items = ret1;
ret.push(item);
}
});
return ret;
}
}