2016-05-18 50 views
1

我有一套由後端API返回的JSON數據,我需要遍歷現有的數組並獲得index用於splice,因此我使用indexOf方法結合了過濾器函數從角度。Angularjs通過過濾器得到indexOf

我能夠從現有的數組中過濾數據,但是我無法獲得數組的索引,它返回-1

這是怎麼做到的。

JS

angular.forEach($scope.data, function(){ 
    var index = $scope.Tablelist.indexOf($filter('filter')($scope.Tablelist,{id: $scope.data.id},true)); 
    console.log($filter('filter')($scope.Tablelist,{id: $scope.data.id},true)); 
    console.log(index); 
}) 

回答

3

$filter返回數組,您需要從中獲取第一個元素,然後使用indexOf進行搜索:

var index = $scope.Tablelist.indexOf(
       $filter('filter')($scope.Tablelist,{id: $scope.data.id},true)[0] 
      ); 

但是,我只是使用Array.prototype.findIndex()。它會快得多,因爲它不會迭代超過它所需的Tablelist

var index = $scope.Tablelist.findIndex(function(item) { 
    return item.id === $scope.data.id; 
}); 

或常規for循環,如果你想更好的瀏覽器兼容性:

var index = -1; 
for (var i = 0; i < $scope.Tablelist.length; i++) 
    if ($scope.Tablelist[i].id === $scope.data.id) { 
     index = i; 
     break; 
    } 
} 
+0

護理解釋爲什麼你會用,而不是過濾findIndex? –

+1

速度。使用'filter'方法,它將迭代'Tablelist'兩次。一次用'filter'找到正確的項目,然後再次在'indexOf'中找到。使用'findIndex'只會迭代一次,直到它找到第一個匹配。 – 4castle

+0

不錯,我會用方法去,非常感謝你 –

2

嘗試這種情況:

var object = $filter('filter')($scope.Tablelist, function (d) { 
    return d.id === $scope.data.id; 
})[0] 
console.log(object); 
console.log($scope.Tablelist.indexOf(object); 
1
$filter('filter')($scope.Tablelist,{id: $scope.data.id},true) 

返回長度爲1的陣列,而不是物品本身。

$filter('filter')($scope.Tablelist,{id: $scope.data.id},true)[0] 

可以做的伎倆

1

$filter返回一個數組,你正在努力尋找你的Tablelist返回-1是數組的索引,請嘗試:

var index = 
    $scope.Tablelist.indexOf($filter('filter')($scope.Tablelist,{id: $scope.data.id},true)[0]));