Search code examples
angularfilterangular2-servicesangular-pipe

Using Filter Pipe In Angular 4


I'm using a filter pipe in my angular 4 application. But I have a problem since i'm filtering inside an array but also inside of that array. So i can't find that specific name... since i can only find the first array but not the inner array. Here's my JSON response and my pipe code below. Here i can only search the "admin name and email" BUT i can't search the "Outlet name, address AND Role name"

JSON

{
  "token": "eyefqffiwqnrfoqif",
  "users": [
    {
      "id": 1,
      "name": "Admin",
      "email": "admin@yahoo.com",
      "created_at": "2018-01-05 07:17:41",
      "updated_at": "2018-01-05 09:17:41",
      "outlet": {
      "id": 1,
      "name": "Sarawak Energy Berhad",
      "address": "Kuching City",
      "contact_number": "1300-88-3111",
      "created_at": "2018-01-05 10:17:44",
      "updated_at": "2018-01-05 10:17:44"
    },
      "roles": [
        {
          "id": 1,
          "name": "Admin",
          "created_at": "2018-01-05 10:17:40",
          "updated_at": "2018-01-05 10:17:40",
          "pivot": {
            "model_id": 1,
            "role_id": 1
          },
        }
      ]
    }
  ]
}

FILTER PIPE

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

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {
  transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){
        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
          return true;
        }
      }
      return false;
    });
  }
}

Solution

  • In this case your outlet is another object inside your each array object, so you need to specifically add a filter for the outlet as follows,

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
     transform(items: any, term: any): any {
        if (term === undefined) return items;
    
        return items.filter(function(item) {
          for(let property in item){
    
            if (item[property] === null){
              continue;
            }
            if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
              return true;
            }
             if(property ='outlet'){
               if(item[property].name.toString().toLowerCase().includes(term.toLowerCase())){
               console.log(item[property].name);
              return true;
             }
    
            }
             if(property ='roles'){
             if (item[property].filter(e => e.name === term.toLowerCase()).length > 0) {
              return true;
             }
    
            }
           }
          return false;
        });
      }
    
    }
    

    DEMO STACKBLITZ