AngularJS从包含对象的数组中过滤掉

angularjs filter from array that contains object

本文关键字:过滤 数组 包含 对象 AngularJS      更新时间:2023-09-26

这可能很简单,但我不确定该怎么做。我已经创建了两个作用域数组(不确定控制器中是否需要)和控制器中的实际列表

$scope.tagFilter = [{tag_id:1,tag_name:test},{tag_id:2,tag_name:test2}];
$scope.categoryFilter = [{cat_id:1,cat_name:test3},{cat_id:2,cat_name:test4}]

我的实际列表

$scope.list = [{list_id:1,category_id:1,tag:1},...]

是否可以创建一个过滤器,我可以在其中tag_id与列表中的标签进行比较,并将cat_id与category_id进行比较我正在考虑创建angular.module.filter,但不确定该怎么做

您可以编写一个 filter 函数,其行为方式如下:

var allowed_tags = $scope.tagFilter.map(function(item){
    return item.tag_id;
})
var allowed_cat = $scope.categoryFilter.map(function(item){
    return item.cat_id;
})
var filtered = $scope.list.filter(function(i){
return ((allowed_tags.indexOf(i.tag) != -1) && 
        (allowed_cat.indexOf(i.category_id) != -1));
})
console.log(filtered);