简体   繁体   中英

Angular.js filter by element of array

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.

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 )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM