2016-12-28 109 views
1

中创建类似sql的管道是否可以根据多个字段创建用于过滤数组的管道?但这些字段可以更改,因此筛选器功能必须包含所有包含的字段。是否有可能在

values.filter((value) => value[field] === args[0] || .... || value[field] === args[n]) 

那么如何创建这样的管道? 过滤器功能情况如何处理?

回答

0

创建过滤器的搜索管道如下。它将接受第一个参数作为主要对象,它保存所有值和第二个参数保持值对象,您必须从主要对象中进行过滤。

定义对象:

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> 

输出:

enter image description here

+0

感谢您的帖子,但我的目标是通过使用对象的属性过滤数组。 –

+0

我认为我的文章可以帮助你,你必须在你的逻辑中做一些修改 –

0

@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; 
      } 

     } 
    } 

所以我可以过滤我想要的数组。