如何检查一个值是否是 angular 中数组的 属性?

How to check if a value is a property of an array in angular?

我正在 angular.js 中制作过滤器。我正在尝试过滤所有包含用户 ID 的项目。如何检查用户 ID 是否在项目数组中?

用户的id是这个数组的属性:$scope.items.user.id

$scope.yourItemFilter = function(item) {

    //$scope.items is an array ($scope.items.user.id = undefined)
    if ($.inArray(item.user.id, $scope.items.user.id)) {
        return item;
    }

    return;
}

我可以在 $scope.items 上执行 foreach,然后将每个 $scope.item.user.id 放入一个数组中。但这似乎不是一个好方法

我认为这对你有用

if ($.inArray(item.user, $scope.items.user) && (item.user.id == $scope.items.user[$.inArray(item.user, $scope.items.user)].id))

$.inArray returns 元素在数组中的索引,考虑这个:

$.inArray('a', ['a', 'b', 'c']); // 0
$.inArray('c', ['a', 'b', 'c']); // 2
$.inArray('d', ['a', 'b', 'c']); // -1

所以你需要输出:

if ($.inArray('a', ['a', 'b', 'c']) > -1) {
  // true
}

您可以使用 for...of 循环并在匹配后立即 return:

$scope.yourItemFilter = function(item) {
    for (var scope_item of $scope.items) {
        if (scope_item.user.id === item.user.id) return item;
    }
}

请注意,默认情况下,您不需要最终 return 作为函数 return undefined

使用 .some() 的替代方法:

$scope.yourItemFilter = function(item) {
    if ($scope.items.some(function (scope_item) {            
        return (scope_item.user.id === item.user.id) 
    })) return item;
}

或者如果你有 ES6 箭头支持:

$scope.yourItemFilter = function(item) {
    if ($scope.items.some(scope_item => scope_item.user.id === item.user.id)) return item;
}