11

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

I have an array of customers rendered in a table with a search box, if the user types a value I want to search for all properties values to push a customer that matches the value typed.

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'},
];

The 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 the name. I'm not sure how to approach this. Should I create a method for the Customer object that returns all property values concatenated and then search for the term on this concatenated value?

J.Rem
  • 545
  • 2
  • 6
  • 24

3 Answers3

12

You need to apply null check and use .toString() otherwise if value will be number it will not be able to use toLowerCase() method and will raise error.

return items.filter(item =>
  Object.keys(item).some(
    k =>
      item[k] != null &&
      item[k]
        .toString()
        .toLowerCase()
        .includes(term.toLowerCase())
  )
);
Aamir
  • 695
  • 10
  • 11
7

You can loop over the keys of the item and see if any of them include the string, and return true if any number of them match:

return items.filter(item =>
  Object.keys(item).some(k => item[k].includes(term.toLowerCase());
)
chrispy
  • 3,552
  • 1
  • 11
  • 19
-1
`arrayObj = [
  {name: 'Maxim', age: 15},
  {name: 'Pasha', age: 35},
  {name: 'Lena', age: 25},
];

let filteredObj = arrayObj.filter((item: any) => {
  if (JSON.stringify(item).includes('Maxim')) {
    return item;
  }
});`

It would not be bad to bring it to a single register.

Maxim Pak
  • 1
  • 2
  • 1
    All posts on stackoverflow.com [must be in English](https://meta.stackexchange.com/questions/13676/). Please [edit] your post to be in English. Alternatively, visit [Stack Overflow на русском](https://ru.stackoverflow.com/). [From Review](https://stackoverflow.com/review/low-quality-posts/29216312) – Ian Campbell Jun 17 '21 at 13:46