Search code examples
javascripthtmlangulartypescriptangular-pipe

How to add filter pipe to a property of an array of object having undefined value


I am working on an Angular 8 project and I have an array of object with the following values:

let studentArray = [ {
 Name: 'Anu',
 Mark: 50,
 IsPassed: true
},
{
 Name: 'Raj',
 Mark: 20,
 IsPassed: false
},
{
 Name: 'Tom',
 Mark: 15
}]

Here, you can see Raj and Tom are failed students. I need to show only details of the student who are failed. To filter this array, I have added a filter.pipe.ts and the code is given below:

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

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(list: any[], key: string, value: any): any {
    return list.filter(i => i[key] === value);
  }

}

Then I added the filter pipe on my HTML page like follows:

<div *ngFor="let item of studentArray | filter : 'IsPassed' : false;"> 
....
....
</div>

I couldn't able to filter this array using my filter.pipe.ts. Is anything wrong here?

Actually, the 'IsPassed' property for 'Tom' is 'undefined' and it is a nullable property. I need to treat undefined as 'false'. But considering my requirement, I can't able to filter studentArray from .ts file. I need a solution to filter this array from the HTML page itself.

I have added my code to the following 'stackblitz' link:

https://stackblitz.com/edit/filter-pipe-puagzk?file=app%2Fhello.component.ts


Solution

  • You have to evaluate whether you want to compare against true or false first. Then check which entry matches.

    return list.filter(i => (value) ?  !!(i[key]) : !(i[key]));