Last active
May 7, 2018 21:26
-
-
Save jamesguan/ba85b1a1e1afbfd3c9db6c674cfff2e8 to your computer and use it in GitHub Desktop.
Angular 2+ Search Pipe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
@Pipe({name: 'searchFilter'}) | |
export class SearchFilterPipe implements PipeTransform { | |
iterate(obj, searchText) { | |
for (let property in obj) { | |
if (obj.hasOwnProperty(property)) { | |
if (typeof obj[property] === "object") { | |
if (this.iterate(obj[property], searchText)){ | |
return true; | |
} | |
} else { | |
if (String(obj[property]).toLowerCase().includes(searchText)){ | |
return true; | |
} | |
} | |
} | |
} | |
return false; | |
} | |
transform(items: any[], searchText: string): any[] { | |
if(!items) return []; | |
if(!searchText) return items; | |
searchText = searchText.toLowerCase(); | |
return items.filter( it => { | |
switch(typeof(it)){ | |
case 'string': | |
return it.toLowerCase().includes(searchText); | |
case 'object': | |
return this.iterate(it, searchText); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment