Seeking guidance on creating a search pipe for Angular 2 to filter nested objects based on a search term. A basic version is up and running, but encountering two issues.
The first issue involves hard coding key names or resorting to using JSON.stringify
, both methods seem less than ideal. Are there more elegant ways to achieve filtering while excluding certain keys like _id
and url
?
Secondly, struggling with filtering multiple terms when the search string contains space(s) and need to filter objects matching all provided terms. Splitting the search term with spaces is possible using terms = term.split(' ')
, but unsure how to proceed with filtering by multiple terms.
Current code snippet:
import {Pipe} from 'angular2/core';
@Pipe({
name: "search"
})
export class SearchPipe{
transform(obj: any, [term]) {
if (obj != null && term) {
return obj.filter( el => {
//var test = JSON.stringify(el);
//return test.toLowerCase().includes(term.toLowerCase()); //trows a compile error but seems to work.
return el.name.toLowerCase().includes(term.toLowerCase()) || el.place.toLowerCase().includes(term.toLowerCase()) || el.title.toLowerCase().includes(term.toLowerCase()) ;
});
} else {
return obj;
}
}
}
Expected input format:
[
{
"_id": "56ffbe512ba199777d51c6ae",
"picture": "http://placehold.it/36x36",
"name": "Melissa Reeves",
"company": "Orbixtar",
"place": "Greenwich, Belarus",
"title": "voluptate est ipsum",
"location": {
"lat": -78.926961,
"lng": 90.157653
},
"url": "http://lol.lol"
},
{
"_id": "56ffbe5119cf66e94b3800b4",
"picture": "http://placehold.it/36x36",
"name": "Chelsea Lindsay",
"company": "Squish",
"place": "Vowinckel, Belarus",
"title": "anim ea exercitation",
"location": {
"lat": 66.547582,
"lng": 162.720388
},
"url": "http://lol.lol"
}
]
If the term is "term1"
it should return objects containing "term1".
For example, the term "Melissa"
should only return the first object in the list.