how to get index position of an array item in cont

2019-03-15 18:46发布

问题:

I have an array with list of values.

 [Object { id="5", country="UAE"}, Object { id="4", country="India"}]

I want to get the index of array item based on the value present in the id. How can I get the index position of an array item with value of id = 4 in angularJS Controller?

回答1:

The angularjs way (using $filter) would be something like this

app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {

    //array
    var items = [{  id: "5", country: "UAE" }, { id: "4",  country: "India" }];

    //search value
    var id2Search = "4";

    //filter the array
    var foundItem = $filter('filter')(items, { id: id2Search  }, true)[0];

    //get the index
    var index = items.indexOf(foundItem );
}]);


回答2:

this is not angularjs specific problem but normal javascript. just loop and return the index

var list =  [{ id="5", country="UAE"}, { id="4", country="India"}];

for (var i = 0; i < list.length ; i++) {
        if (list[i][id] === 4) {
            return i;
        }
 }

you can then make it generic by making it function on array which accepts the value and property name

Array.prototype.getIndexOfObject = function(prop, value){
   for (var i = 0; i < this.length ; i++) {
            if (this[i][prop] === value) {
                return i;
            }
     }
}


回答3:

You can use the map() function to iterate over each object in your array and inspect any desired property. For example if you have an array of objects

$scope.items = 
[
{'id':'1','name':'item1'},
{'id':'2','name':'item2'}
];

to get the index of the second object in the array use

var index = $scope.items.map(function (item) {
            return item.id;
        }).indexOf(2);

returns the index of the object containing the value of 2 in the id property.