I have an array of nested json objects like this:
[{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}]
I want to have a pipe which filters every object having values matching with a given argument.
On this purpose, I created a pipe which uses a Array.prototype.filter
as following:
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(items: any[], args: string): any {
if(!args){
return items;
} else {
return items.filter(item => item.name.en.toLowerCase().indexOf(args[0]) !== -1); //returns every name.en values matching with args
}
}
}
This allows me to filter by name.en. How can I make it able to filter the values name.en
and name.it
too?
You can use OR operator when filtering.
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(items: any[], args: string): any {
if (!args){
return items;
} else {
return items
.filter(item =>
item.name.en.toLowerCase().indexOf(args[0]) !== -1 || item.name.it.toLowerCase().indexOf(args[1]) !== -1
);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.