I have an array with objects. I want to find a specific object's index. This object has an unique id
property' value , and i can find it with a $filter
:
var el = $filter('filter')( tabs, { id: id })[0]; // "el" is my unique element
But how can i know what is the index of this element in it's original array? Does $filter
can provide me this information?
By now i didn't find an Angular solution, because i can't get much useful info on this page . So i have used Array
's indexOf
method :
var el_index = tabs.indexOf( el );
To get indexes of all elements with specific id
we go the similar way:
$scope.getTabsIndexes = function(id){
var els = $filter('filter')( tabs , { id: id });
var indexes = [];
if(els.length) {
var last_i=0;
while( els.length ){
indexes.push( last_i = tabs.indexOf( els.shift() , last_i ) );
}
}
return indexes;
}
But it is too long and i'm sure that i'm reinventing the wheel here...
Try this option:
$scope.search = function(selectedItem) {
$filter('filter')($scope.tabs, function(item) {
if(selectedItem == item.id){
$scope.indexes.push( $scope.tabs.indexOf(item) );
return true;
}
return false;
});
}
I think it a bit short and clear.
See Fiddle
我发现这更简单,更易读
index = ar.findIndex(e => e.id == 2);
Not sure why you need the original index, but you can add the original index as a new property to the object itself. Eg: write a filter to add the idx:
angular.module('yourModule', [])
.filter('addId', [function() {
return function(arrObj) {
for (var i = 0; i < arrObj.length; ++i) {
arrObj[i].$$originalIdx = i;
}
return arrObj;
};
}]);
Then you can get this expression in html:
{{ tabs | addIdx | filter:{id: 777} }}
Or in javascript:
$scope.getTabIndex = function(id){
var el = $filter('filter')( addId(tabs) , { id: id })[0];
var el_index = el.$$originalIdx;
return el_index;
};
Somehow I can't get it work on jsfiddle, it seems to have trouble with the dependencies injection..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.