【问题标题】:How to check if a value is a property of an array in angular?如何检查一个值是否是角度数组的属性?
【发布时间】:2016-09-17 09:16:18
【问题描述】:

我正在 angular.js 中制作一个过滤器。如果它们包含用户 ID,我正在尝试过滤所有项目。如何检查用户 id 是否在 items 数组中?

用户的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 放入一个数组中。但这似乎不是一个好方法

【问题讨论】:

  • $scope.items.user.id数组吗?
  • 不,这应该是所有 $scope.items.user.id 的数组,所以首先我想在执行此功能之前将所有这些与 foreach 一起放入数组中。但我正在寻找更好的方法

标签: javascript arrays angularjs angularjs-filter


【解决方案1】:

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

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

请注意,您不需要最终的 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;
}

【讨论】:

  • 您能否给出一些反馈意见,这个答案或任何其他答案是否回答了您的问题?
【解决方案2】:

$.inArray 返回数组中元素的索引,考虑一下:

$.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
}

【讨论】:

    【解决方案3】:

    我认为这对你有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-03
      • 2016-09-24
      • 1970-01-01
      • 2017-10-20
      • 2018-06-09
      • 2014-05-16
      • 1970-01-01
      • 2021-05-28
      相关资源
      最近更新 更多