【问题标题】:How to find index of javascript array of object if value is given? [duplicate]如果给定值,如何找到对象的javascript数组的索引? [复制]
【发布时间】:2017-08-08 09:05:06
【问题描述】:

这是我的对象数组:

$scope.choices =  [
  {
     id: 0,
     product: [{id:'0'}] 
  }, 
  {
    id: 10,
    product: [{id:'5'}]
  }
];

如何找到 id 值“10”的索引号?

【问题讨论】:

    标签: javascript angularjs arrays


    【解决方案1】:

    你可以用这个:

    var reqIndex;
    $scope.choices.forEach(function(choice, index) {
        if (choice.id === 10) {
            reqIndex= index;
            return
        }
    })
    

    【讨论】:

      【解决方案2】:

      试试这个

      $scope.choices.findIndex(function(x) {
         return x.id==10;
      });
      

      【讨论】:

        【解决方案3】:

        让下面是你要在数组中搜索的对象

        var searchObject={
            id: 0,
            product: [{id:'0'}] 
        };
        

        现在使用以下

        $scope.choices.indexOf(searchObject);
        

        希望这会有所帮助:)

        【解决方案4】:

        如果你喜欢使用纯javascript并且使用没问题,你可以使用以下

        function findWithAttr(array, attr, value) {
            for(var i = 0; i < array.length; i += 1) {
                if(array[i][attr] === value) {
                    return i;
                }
            }
            return -1;
        }
        
        findWithAttr(choices, 'id', 10);
        

        或者,您可以使用以下函数

          $scope.findIndex=function(){
        
                    angular.forEach( $scope.choices,function(object,index){
                             console.log(object);
                            if(object.id==10){
                                console.log('index'+index);
                            }
        
        
                        })
        
        
                };
        

        【讨论】:

          【解决方案5】:

          您可以使用Object.keys() 检索您对象的所有键,然后对其进行迭代以查找是否有一个具有相应值的键。

          【讨论】:

            猜你喜欢
            • 2021-05-18
            • 2014-09-20
            • 1970-01-01
            • 2020-09-27
            • 2010-12-27
            • 2021-11-07
            • 1970-01-01
            • 2012-11-24
            • 1970-01-01
            相关资源
            最近更新 更多