1
中創建類似sql的管道是否可以根據多個字段創建用於過濾數組的管道?但這些字段可以更改,因此篩選器功能必須包含所有包含的字段。是否有可能在
values.filter((value) => value[field] === args[0] || .... || value[field] === args[n])
那麼如何創建這樣的管道? 過濾器功能情況如何處理?
中創建類似sql的管道是否可以根據多個字段創建用於過濾數組的管道?但這些字段可以更改,因此篩選器功能必須包含所有包含的字段。是否有可能在
values.filter((value) => value[field] === args[0] || .... || value[field] === args[n])
那麼如何創建這樣的管道? 過濾器功能情況如何處理?
創建過濾器的搜索管道如下。它將接受第一個參數作爲主要對象,它保存所有值和第二個參數保持值對象,您必須從主要對象中進行過濾。
定義對象:
data: any[];
searchValue:any[];
constructor(){
this.data = [ 'apple', 'banana', 'carrot', 'pear', 'peach', 'orange','mango', 'grapes', 'lime', 'lemon' ];
this.searchValue = [ 'apple', 'peach', 'orange' ]
}
搜索管:
export class SearchPipe implements PipeTransform {
transform(items:any[], args:string[]):any[] {
if (typeof items === 'object') {
var resultArray = [];
if (args.length === 0) {
resultArray = items;
}
else {
for (let item of items) {
if (item != null && args.indexOf(item)>=0) {
resultArray.push(item);
}
}
}
return resultArray;
}
else {
return null;
}
}
}
HTML:
<div class="item" *ngFor="let item of data | searchPipe: searchValue">
{{item}}
</div>
輸出:
@sandip帕特爾謝謝您的回答。 我稍微修改了你的答案。
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: 'inFilter',
pure: false
})
export class InFilterPipe implements PipeTransform {
transform(items: any[], args: any): any[] {
if (typeof items === 'object') {
var resultArray = [];
if (args.args.length === 0) {
resultArray = items;
}
else {
for (let item of items) {
if (item != null && args.args.indexOf(item[args.key]) >= 0) {
resultArray.push(item);
}
}
}
return resultArray;
}
else {
return null;
}
}
}
所以我可以過濾我想要的數組。
感謝您的帖子,但我的目標是通過使用對象的屬性過濾數組。 –
我認爲我的文章可以幫助你,你必須在你的邏輯中做一些修改 –