Q:

Angular Custom pipe implementation with dynamic key and search text

I have implemented custom pipe as below.
 @Pipe({
      name: 'search'
    })
    export class SearchPipe implements PipeTransform {

      transform(items: any[], searchText?: string): any {
        if (!items) return [];
        if (!searchText) return items;
        searchText = searchText.toLowerCase();
        return items.filter((item) => {
          return item.name.toLowerCase().includes(searchText);
        });
      }
}

here item.name is hard coded.
so i want to pass key name dynamically along with searchText.
so i can use it across application how to do it let me know.

A:

Please try below code, i have added an extra parameter key.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string, key?:string): any[] {
    if (!items) return [];
    if (!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter(it => {
      if(!key){
        return it.toLowerCase().includes(searchText);
      } else {
        return it[key].toLowerCase().includes(searchText);
      }
    });
  }
}

