我的数据看起来像这样
[
{id: 1234,
Name: 'John',
Tags: ['tag1', 'tag2']
},
{id: 1235,
Name: 'Mike',
Tags: ['tag1', 'tag3']
}
]
我希望能够输入搜索栏并过滤数据以搜索相关标签。在角度1中有一个内置的过滤管道,但看起来它已经被角度2移除了。我一直在寻找自定义管道,但我能想到的唯一方法是使用嵌套循环循环遍历所有对象然后遍历标记。我在考虑这个错误。是否有更简单的方法来执行此操作或内置函数可以为此工作?
答案 0 :(得分:2)
您可以使用普通的JavaScript API来获取该行为:
data = [
{id: 1234,
Name: 'John',
Tags: ['tag1', 'tag2']
},
{id: 1235,
Name: 'Mike',
Tags: ['tag1', 'tag3']
}
];
filterDataByTag(searchTerm: string) {
// filter the data array, based on some condition
return this.data.filter(item => {
// only include an item in the filtered results
// if that item's Tags property includes the searchTerm
// includes is a built in array method in ES2016
return item.Tags.includes(searchTerm);
});
}
在我的示例中,我正在对data
进行编码,但您可以根据自己的情况进行调整。关键点是函数根据searchTerm返回data
的过滤列表,因此每次要刷新过滤后的列表时都可以调用此方法(例如,对于您的输入事件)搜索字段)
答案 1 :(得分:0)
您应该将数据重新组织到反向索引存储中:
export interface StoreData {
Tag: string;
Peoples: People[] = [];
}
const store: StoreData[] = [];
export interface People {
id: number;
Name: string;
Tags: string[];
}
loadPeopleStore(peoples: People) {
peoples.forEach(p => {
p.Tags.forEach(t => {
let storeData = store.filter(d => d.Tag === t);
if(storeData.length == 1) {
storeData[0].Peoples.push(p);
} else {
store.push({Tag: t, Peoples[p]});
}
}
}
}
initYourPipe() {
let peoples: People[] = [
{id: 1234,
Name: 'John',
Tags: ['tag1', 'tag2']
},
{id: 1235,
Name: 'Mike',
Tags: ['tag1', 'tag3']
}
]
this.loadPeopleStore(peoples);
}