如何搜索所有值?

时间:2018-02-03 14:18:03

标签: angular typescript

如何实现对Angular2的所有值的搜索。这是代码:

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

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(projects: any, search: any): any {
  if(search === undefined) return projects;

    return projects.filter(function(project)
    {
    return project.name.toLowerCase().includes(search.toLowerCase());
    })

  }

}

目前它只能按名称搜索,以及如何制作以便他可以查看表格中的所有值(例如,id,姓名,姓氏,国家等)

2 个答案:

答案 0 :(得分:0)

 return projects.filter(function(project)
{
      return project.name.toLowerCase().includes(search.toLowerCase())
      ||
      return project.id.toLowerCase().includes(search.toLowerCase())
      ||
      return project.surname.toLowerCase().includes(search.toLowerCase())
      ||
      ...
       ;
})

或者您可以查看Array filtering on multiple fields

之类的内容

答案 1 :(得分:0)

如果对象只有1级深度,你可以直接通过所有键并在进行比较之前连接所有值。

它看起来像这样。

function search(projects, search) {
    return projects.filter(p => {
        return Object
            .keys(p) // get all keys
            .map(k => p[k]) // get all values
            .reduce((prev, current) => prev + current, '') // concat
            .toLowerCase() // lowercase
            .includes(search.toLowerCase()); compare
    });

以管道形式。

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

@Pipe({
    name: 'filter'
})
export class FilterPipe implements PipeTransform {

    transform(projects: any, search: any): any {
         if(search === undefined) return projects;
         return projects.filter(p => {
            return Object
                .keys(p)
                .map(k => p[k])
                .reduce((prev, current) => prev + current, '')
                .toLowerCase()
                .includes(search.toLowerCase());
        });

    }

}