how to get index position of an array item in controller passing a value in angularjs

泪湿孤枕 提交于 2019-12-09 04:42:45

问题


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.




回答4:


Pass the id that you want to remove from the array to the given function from the controller (function can be in the same controller but prefer to keep it in a service).

  function removeInfo(id) {
    let item = Object .filter(function(item) {
      return Object.id === id;
    })[0];
    let index = Object.indexOf(item);
  }


来源:https://stackoverflow.com/questions/24262569/how-to-get-index-position-of-an-array-item-in-controller-passing-a-value-in-angu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!