Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find index of the object an array angularjs

for example I have this array :

  $scope.records = [
    {
      "Name" : "Alfreds Futterkiste",
      "Country" : "Germany"
    },
    {
      "Name" : "Berglunds snabbköp",
      "Country" : "Sweden"
    },
    {
      "Name" : "Centro comercial Moctezuma",
      "Country" : "Mexico"
    },
    {
      "Name" : "Ernst Handel",
      "Country" : "Austria"
    }
  ];

How to get value index from object? with example "Country" : "Austria" this index is 3

like image 336
Edu Arif Avatar asked Oct 12 '16 12:10

Edu Arif


2 Answers

Use findIndex method - 
   var index = $scope.records.findIndex(x=>x.Country==='Austria')
like image 158
Chetan Avatar answered Oct 04 '22 22:10

Chetan


You could use Array.findIndex in the latest browsers, but there's no support for this in Internet Explorer, only Edge

let $scope = {};

$scope.records = [
    {
      "Name" : "Alfreds Futterkiste",
      "Country" : "Germany"
    },
    {
      "Name" : "Berglunds snabbköp",
      "Country" : "Sweden"
    },
    {
      "Name" : "Centro comercial Moctezuma",
      "Country" : "Mexico"
    },
    {
      "Name" : "Ernst Handel",
      "Country" : "Austria"
    }
];

let index = $scope.records.findIndex( record => record.Country === "Austria" );

console.log(index); // 3

For support in IE9 and up, you could use Array.some instead

var $scope = {};

$scope.records = [{
  "Name": "Alfreds Futterkiste",
  "Country": "Germany"
}, {
  "Name": "Berglunds snabbköp",
  "Country": "Sweden"
}, {
  "Name": "Centro comercial Moctezuma",
  "Country": "Mexico"
}, {
  "Name": "Ernst Handel",
  "Country": "Austria"
}];

var index = -1;

$scope.records.some(function(obj, i) {
  return obj.Country === "Austria" ? index = i : false;
});

console.log(index);
like image 41
adeneo Avatar answered Oct 04 '22 20:10

adeneo