Finding a string in all properties of an object in Angular 2

How to search a string in all properties of an object in Angular 2 using TS.

I have an array of clients displayed in a table with a search field if the user enters a value that I want to find across all property values ​​in order to push a client that matches the entered value.

export var CUSTOMER: Client[] = [
  { id: 1, name: 'John', phone: '888-888-888'},
  { id: 2, name: 'Nick', phone: '555-888-888'},
  { id: 3, name: 'Mike', phone: '666-888-888'},
];

Filter pipe

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

@Pipe({
  name: 'filter',
  pure: false
})
@Injectable()
export class Ng2SearchPipe implements PipeTransform {

  transform(items: any, term: any): any {
    if (term === undefined) {
      return items;
    }

    return items.filter(function(item){
      return item.name.toLowerCase().includes(term.toLowerCase());
    });
  }
}

In the filter pipe above I can only search by name. I am not sure how to approach this. Should I create a method for the Customer object that returns all the combined values ​​of the properties, and then search for that combined value?

+8
source share
2 answers

.toString() , , toLowerCase() .

return items.filter(item =>
  Object.keys(item).some(
    k =>
      item[k] != null &&
      item[k]
        .toString()
        .toLowerCase()
        .includes(term.toLowerCase())
  )
);
+6

, - , true, :

return items.filter(item =>
  Object.keys(item).some(k => item[k].includes(term.toLowerCase());
)
+5

Source: https://habr.com/ru/post/1668040/


All Articles