首页 > 解决方案 > 在多个字段上搜索管道以查找一组项目

问题描述

我有一个管道用于搜索一组用户的 ID 或名称。它工作正常。如果我写下用户 ID 号,它会找到它。如果我写名字,它只会在名字按顺序写的情况下找到

但我想搜索名字和姓氏的例子,并得到名字为第二个名字的用户,第三个名字为姓氏

我知道我必须拆分查询字符串( splitted = querystring.split(' ') 并搜索这两个名称,但我不知道如何。

我不想要 2 个术语的静态搜索,而是 2、3 等的动态搜索……用户想要的那些。

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({
  name: 'querystring'
})
@Injectable()
export class PesquisaPipe implements PipeTransform {
  transform(users: any[], querystring: any): any[] {
   if ( querystring=== undefined) {
     return users;
   }
   return users.filter(z => {
     const userID = z.userID.toString().includes(querystring.toLocaleLowerCase());
     const userName = z.userName.toLocaleLowerCase().includes(querystring.toLocaleLowerCase());
     return( userID + userName);
   });
  }

标签: angulartypescript

解决方案


欢迎来到堆栈溢出!

首先,使用管道进行过滤或排序是个坏主意。文档在这里对此提出警告:https ://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

相反,在代码中进行过滤。

其次,有几种方法可以处理多个案例的过滤,我在这里有一篇博客文章:https ://blogs.msmvps.com/deborahk/filtering-in-angular/

通常,您可以使用 OR || 过滤多个条件。如下:

performFilter(filterBy: string): IProduct[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.products.filter((product: IProduct) =>
          product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1 || 
          product.description.toLocaleLowerCase().indexOf(filterBy) !== -1);
}

如果在productNameOR中找到,上面的代码会归档一个指定的字符串description

或者您可以过滤任何对象属性,如下所示:

performFilter(filterBy: string): IProduct[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.products.filter((product: IProduct) => 
        Object.keys(product).some(prop => {
            let value = product[prop];
            if (typeof value === "string") {
                value = value.toLocaleLowerCase();
            } 
            return value.toString().indexOf(filterBy) !== -1;
        })    
    );
}

上面的代码在对象的所有属性中搜索特定提供的字符串。

链接的博客文章提供了其他选项。

将此应用于我认为您要问的问题:

performFilter(filterBy: string): User[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.users.filter((user: User) =>
          user.name.toLocaleLowerCase().indexOf(filterBy) !== -1 || 
          user.userId.toLocaleLowerCase().indexOf(filterBy) !== -1 ||
          user.userName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}

推荐阅读