根据其属性获取数组元素的索引 [英] Getting index of an array's element based on its properties

查看:26
本文介绍了根据其属性获取数组元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JavaScript 对象数组,如下所示:

I have a JavaScript array of objects like this:

var myArray = [{...}, {...}, {...}];

每个对象在其他属性中都有唯一的id:

Each object has unique id among other properties:

{ 
  id: 4,
  property1: 'something',
  property2: 'something'
}

如果我只知道它的 id 属性,我如何获得该数组中特定对象的索引?所以如果我知道myArray[x].id == 4,我怎么能找到x?

How can I get an index of a particular object in that array, if I only know its id property? So if I know that myArray[x].id == 4, how can I find x?

推荐答案

var index = myArray.map(function(el) {
  return el.id;
}).indexOf(4);

对于版本 9 以下的 IE,map 需要一个补丁,或者只是使用一个循环.

For IE below version 9, map need a patch, or just use a loop.

这篇关于根据其属性获取数组元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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