查找对象的索引数组angularjs [英] find index of the object an array angularjs

查看:97
本文介绍了查找对象的索引数组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"
    }
  ];

如何从对象获取价值指数?例如国家:奥地利这个指数是3

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

推荐答案

你可以使用 Array.findIndex 在最新的浏览器中,但在Internet Explorer中不支持此功能,只有Edge

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

对于IE9及以上版本的支持,您可以使用 Array.some 而不是

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);

这篇关于查找对象的索引数组angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆