在对象的数组,最快的方式找到一个对象,其属性匹配搜索的索引 [英] In an array of objects, fastest way to find the index of an object whose attributes match a search

查看:383
本文介绍了在对象的数组,最快的方式找到一个对象,其属性匹配搜索的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在冲浪附近有一座小试图找到一种有效的方式做到这一点,但已经变得没有出路的。我有对象的数组,看起来像这样:

I've been surfing around a little trying to find an efficient way to do this, but have gotten nowhere. I have an array of objects that looks like this:

array[i].id = some number;
array[i].name = some name;

我想要做的是找到其中id等于对象的索引,例如,0,1,2,3一个或4。
我想我可以做这样的事情:

What i want to do is to find the INDEXES of the objects where id is equal to, for example, one of 0,1,2,3 or 4. I suppose I could just do something like :

var indexes = [];
for(i=0; i<array.length; i++) {
  (array[i].id === 0) ? { indexes[0] = i }
  (array[i].id === 1) ? { indexes[1] = i }
  (array[i].id === 2) ? { indexes[2] = i }
  (array[i].id === 3) ? { indexes[3] = i }
  (array[i].id === 4) ? { indexes[4] = i }
}

虽然这工作,看起来是相当昂贵而缓慢(更不用提丑),特别是如果array.length可能很大。如何美化这件事有点什么想法吗?我想以某种方式使用array.indexOf,但我看不出如何强制语法。这

While this would work, it looks to be quite expensive and slow (not to mention ugly), especially if array.length could be large. Any ideas on how to spruce this up a bit? I thought of using array.indexOf somehow but I don't see how to force the syntax. This

array.indexOf(this.id === 0);

例如,返回不确定的,因为它也许应该。
在此先感谢!

for example, returns undefined, as it probably should. Thanks in advance!

推荐答案

也许你想使用高阶函数,如地图。
假设您想通过字段属性进行搜索:

Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:

var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];

这篇关于在对象的数组,最快的方式找到一个对象,其属性匹配搜索的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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