我怎样才能简单直接地找到满足某些条件的对象数组中的索引?

例如,给定这个输入:

var hello = {
    hello: 'world',
    foo: 'bar'
};
var qaz = {
    hello: 'stevie',
    foo: 'baz'
}

var myArray = [];
myArray.push(hello, qaz);

我如何搜索myArray找到其hello属性等于'stevie'的元素的索引(在这种情况下,结果应该是1)?


当前回答

我更喜欢使用findIndex()方法:

 var index = myArray.findIndex('hello','stevie');

Index会给出索引号。

其他回答

你可以使用一个本地方便的函数Array.prototype.findIndex():

如果数组中的元素满足提供的测试函数,则findIndex()方法返回数组中的索引。否则返回-1。

只是需要注意的是,它不支持Internet Explorer, Opera和Safari,但你可以使用下面链接提供的Polyfill。

更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

Var hello = { 你好:“世界”, 喷火:“酒吧” }; Var qaz = { 你好:史蒂夫, 喷火:“记者” } var myArray = []; myArray。推动(你好,qaz); var index = myArray。findIndex(函数(元素,索引,数组){ 如果元素。你好=== 'stevie') { 返回true; } }); Alert ('stevie is at index: ' + index);

我认为你可以用map函数在一行中解决它:

const pos = myArray.map(e => e.hello).indexOf('stevie');

这里的大多数答案并不能解决所有情况。 我发现这个解决方案更好:

const isInarray = myArr.filter((obj) => obj.hello === 'stevie' && obj.foo === 'baz').length > 0;
if (!isInArray) {
 ....
}

你可以使用findIndex()方法:

cosnt myIndex=myArray.findIndex(el=>el.hello==='stevie')

如果myIndex < 0表示不存在

你可以简单地使用

const someId = 2; Const数组= [{id:1}, {id:2}, {id:3}]; 常量索引=数组。Reduce ((i, item, index) => item。id === someId ?索引:i, -1); alert('someId ' + someId + ' is at index ' + index);

没有下划线,没有for,只有一个略读。