Home > Net >  How to find spesific Object type from string value contained in this object's properties
How to find spesific Object type from string value contained in this object's properties

Time:03-12

I want to generate Filter pipe in Angular that works for filtering the Car, Brand and Color array object by it's pipe parameter corresponding their "carName" , "brandName" etc. property.

For example this pipe is going to filter the Colors by their name corresponding the value of filter pipe parameter.

But I want to do that this pipe filters on all Object types with it's(Object's) Name property that i created wherewithal.

To do that, All Objects need to have same "Name" property name. But My Objects has different name properties like;

carName:string (Car)

name:string (Brand)

name:string (Color)

I've created a pipe that works successfully on object that only has "name" properties but I can't make it successful that this pipes works on Car object as well ;

@Pipe({
 name: 'filter',
})



export class FilterPipe implements PipeTransform {

  transform(entityList: any[], filter: string): any[] {

    filteredList: typeof entityList;

if (filter) {
  filter = filter.toLocaleLowerCase();
  return entityList.filter((c) =>
    c.name.toLocaleLowerCase().includes(filter)
  );
}

return entityList;
 

 }
}

How can I create a generic Pipe to filter objects with its(Object's) name property by just the properties of object includes "name" expression ?

CodePudding user response:

I don't know the details - like other properties of your objects and if they're all bundled up in the same array or you actually have arrays of same-type objects, or even how and where you use the pipe - so this is just an example with some asumptions and mock-up data: https://stackblitz.com/edit/base-angular-12-app-qqw1fq

Your pipe could be:

transform(entityList: any[], filter: string): any[] {
    let filteredList = entityList;
    if (filter) {
      filteredList = [];
      filter = filter.toLowerCase();
      entityList.forEach((c) => {
          Object.keys(c).forEach((key, i) => {
              if (key.toLowerCase().includes('name')) {
                  if (c[key].toLowerCase().includes(filter)) {
                      filteredList.push(c);
                  }
              }
          });
      });
    }
    return filteredList;
}
  • Related