Created
September 4, 2017 11:24
-
-
Save jberndsen/30ba9aa224d8a8d3cd4499d1b85adda5 to your computer and use it in GitHub Desktop.
Angular 2+ pipe to filter items based on value of a single prop
This file contains 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: 'filterBy' | |
}) | |
export class FilterByFilter implements PipeTransform { | |
transform(list, arg: string) { | |
if (!list) { | |
return []; | |
} | |
if (!arg) { | |
return list; | |
} | |
return list.filter(item => this.check(item, arg.split('.'))); | |
} | |
private check(item: {}, path: string[]) { | |
const [first, ...rest] = path; | |
if (path.length === 0) { | |
return false; | |
} | |
if (path.length === 1) { | |
return item[first]; | |
} | |
if (path.length > 1) { | |
return this.check(item[first], rest); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment