繁体   English   中英

Angular.js 按数组元素过滤

[英]Angular.js filter by element of array

我有一个 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"]}
 ]

我想做一个搜索引擎。 如果用户可以输入一个或多个单词,那么我的应用程序将过滤我的变量。

例如,用户输入“28”和“MongoDB”,然后我将这两个查询放在一个数组中

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

并用它过滤我的数组:$scope.users。

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

我想知道如何做一个函数或过滤器。

不是很理想,但你可以试试这个

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;
});

演示

 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