Reputation: 1570
I have an array of json obects like:
$scope.users = [
{name:'Maria',age:25,skills["Angular.js","Node.js"]},
{name:'Maxime',age:28,skills["HTML","MongoDB"]},
{name:'Noemie',age:28,skills["CSS","MongoDB"]}
]
i want to make a search engine. if the user can enter one or multiples words and then my app will filter my variable.
For example, the user enter "28" and "MongoDB", then I put the two queries in an array like
$scope.queries = [28,"MongoDB"]
and filter my array : $scope.users with it.
Please note that $scope.users is not as simple as the exemple and it have somes other array wich contain array etc... So i'll prefer a function to "simply" search for keywords
I would like to know how to do a function or filter.
Upvotes: 4
Views: 113
Reputation: 68433
Not very optimal, but you can try this
var filterQueries = [28,"MongoDB"];
var filteredResults = $scope.users.filter(function(obj){
var match = false;
filterQueries.forEach(function(query){
if ( obj.name == query || obj.age == query || obj.skills.indexOf( query ) != -1 )
{
match = true; //assuming you want any of the query to be found rather than all
}
});
return match;
});
DEMO
var users = [
{name:'Maria',age:25,skills : ["Angular.js","Node.js"]},
{name:'Maxime',age:28,skills : ["HTML","MongoDB"]},
{name:'Noemie',age:28,skills : ["CSS","MongoDB"]}
];
var filterQueries = [28,"MongoDB"];
var filteredResults = users.filter(function(obj){
var match = false;
filterQueries.forEach(function(query){
if ( obj.name == query || obj.age == query || obj.skills.indexOf( query ) != -1 )
{
match = true; //assuming you want any of the query to be found rather than all
}
});
return match;
});
document.body.innerHTML += JSON.stringify( filteredResults, 0, 4 )
Upvotes: 2