我怎样才能简单直接地找到满足某些条件的对象数组中的索引?
例如,给定这个输入:
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)?
当前回答
var hello = {hello: "world", foo: "bar"};
var qaz = {hello: "stevie", foo: "baz"};
var myArray = [];
myArray.push(hello,qaz);
function indexOfObject( arr, key, value ) {
var j = -1;
var result = arr.some(function(obj, i) {
j++;
return obj[key] == value;
})
if (!result) {
return -1;
} else {
return j;
};
}
alert(indexOfObject(myArray,"hello","world"));
其他回答
var idx = myArray.reduce( function( cur, val, index ){
if( val.hello === "stevie" && cur === -1 ) {
return index;
}
return cur;
}, -1 );
简单:
myArray.indexOf(myArray.filter(function(item) {
return item.hello == "stevie"
})[0])
你可以使用findIndex()方法:
cosnt myIndex=myArray.findIndex(el=>el.hello==='stevie')
如果myIndex < 0表示不存在
这里的大多数答案并不能解决所有情况。 我发现这个解决方案更好:
const isInarray = myArr.filter((obj) => obj.hello === 'stevie' && obj.foo === 'baz').length > 0;
if (!isInArray) {
....
}
我喜欢Pablo的回答,但是array# indexOf和array# map并不适用于所有浏览器。下划线将使用本机代码,如果它是可用的,但也有回退。另外,它有pluck方法来做Pablo的匿名映射方法所做的事情。
var idx = _.chain(myArray).pluck("hello").indexOf("Stevie").value();