简体   繁体   English

在同一搜索框中搜索多个数组对象属性

[英]In the same search box search by multiple array object properties

searchTerm: any;

search() {

      this.records = this.records.filter((res: any)=>{
        return res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }

I am making the search term with name which is the property or key in records array. 我正在使用name作为搜索项,这是记录数组中的属性或键。 In the same search box I also want to search by age and course. 在同一个搜索框中,我还想按年龄和课程进行搜索。 How can I achieve this. 我怎样才能做到这一点。

<input type ="text" placeholder="search" (input)=" search();" [(ngModel)]="searchTerm">

Just expand you're search filter to include your extra criteria: 只需展开您的搜索过滤器即可添加额外条件:

search() {
      this.records = this.records.filter((res: any)=>{
        return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) || 
        (res.course && res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) || 
        (res.age && res.age.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) ;
      });
  }

This assumes that both course and age are strings in the records array. 这假设课程和年龄都是记录数组中的字符串。

You can try using || 您可以尝试使用|| operator with the same return statement as below : 运算符具有相同的返回语句如下:

this.records = this.records.filter((res: any)=>{
        return (res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()) || res.age.match(this.searchTerm) || res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
});

You could try to combine the conditions with or, for example like this. 您可以尝试将条件与或组合,例如像这样。

search() {

      this.records = this.records.filter((res: any)=>{
        return (res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase() ||
            res.age.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase() ||
            res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }

Try: 尝试:

search() {
    this.records = this.records.filter((res: any)=>{
      return Object.keys(res).some(item => {
        return item.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())
      });
    });
  }

This will search whatever property is in the object and check whether it's value matched the criteria. 这将搜索对象中的任何属性,并检查它的值是否与条件匹配。 It will stop on the first match 它会在第一场比赛中停止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM