简体   繁体   English

Angular.js 按数组元素过滤

[英]Angular.js filter by element of array

I have an array of json obects like:我有一个 json 对象数组,例如:

 $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例如,用户输入“28”和“MongoDB”,然后我将这两个查询放在一个数组中

$scope.queries = [28,"MongoDB"]

and filter my array : $scope.users with it.并用它过滤我的数组:$scope.users。

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请注意 $scope.users 不像示例那么简单,它还有一些其他数组,其中包含数组等......所以我更喜欢一个函数来“简单地”搜索关键字

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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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