我怎样才能简单直接地找到满足某些条件的对象数组中的索引?
例如,给定这个输入:
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var myArray = [];
myArray.push(hello, qaz);
我如何搜索myArray找到其hello属性等于'stevie'的元素的索引(在这种情况下,结果应该是1)?
我怎样才能简单直接地找到满足某些条件的对象数组中的索引?
例如,给定这个输入:
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var myArray = [];
myArray.push(hello, qaz);
我如何搜索myArray找到其hello属性等于'stevie'的元素的索引(在这种情况下,结果应该是1)?
当前回答
我喜欢Pablo的回答,但是array# indexOf和array# map并不适用于所有浏览器。下划线将使用本机代码,如果它是可用的,但也有回退。另外,它有pluck方法来做Pablo的匿名映射方法所做的事情。
var idx = _.chain(myArray).pluck("hello").indexOf("Stevie").value();
其他回答
var idx = myArray.reduce( function( cur, val, index ){
if( val.hello === "stevie" && cur === -1 ) {
return index;
}
return cur;
}, -1 );
如果你只是对这个职位感兴趣,请参阅@Pablo的答案。
pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');
然而,如果你希望找到元素(例如,如果你正在考虑做这样的myArray[pos]),有一个更有效的单行方法来做,使用过滤器。
element = myArray.filter((e) => e.hello === 'stevie')[0];
参见性能结果(~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3
我认为你可以用map函数在一行中解决它:
const pos = myArray.map(e => e.hello).indexOf('stevie');
如果你的对象与你在数组中使用的对象是同一个对象,你应该能够以同样的方式获取对象的索引,就像它是一个字符串一样。
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var qazCLONE = { // new object instance and same structure
hello: 'stevie',
foo: 'baz'
}
var myArray = [hello,qaz];
myArray.indexOf(qaz) // should return 1
myArray.indexOf(qazCLONE) // should return -1
我更喜欢使用findIndex()方法:
var index = myArray.findIndex('hello','stevie');
Index会给出索引号。