一尘不染

查找对象的索引数组angularjs

angularjs

例如我有这个数组:

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

如何从对象获取价值指数?例如“ Country”:“ Austria”,该指数为3


阅读 273

收藏
2020-07-04

共1个答案

一尘不染

您可以Array.findIndex在最新的浏览器中使用,但Internet
Explorer中不支持此功能,只有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

为了在IE9及更高版本中提供支持,您可以Array.some改用

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);
2020-07-04