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

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

问题描述

我一直在网上冲浪,试图找到一种有效的方法来做到这一点,但一无所获.我有一个看起来像这样的对象数组:

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 等于的对象的 INDEXES,例如,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);

例如,返回 undefined,因为它可能应该.

for example, returns undefined, as it probably should.

推荐答案

也许您想使用诸如map"之类的高阶函数.假设您想按 'field' 属性搜索:

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天全站免登陆