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

例如,给定这个输入:

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 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

其他回答

var idx = myArray.reduce( function( cur, val, index ){

    if( val.hello === "stevie" && cur === -1 ) {
        return index;
    }
    return cur;

}, -1 );

你可以创建自己的原型来做到这一点:

喜欢的东西:

Array.prototype.indexOfObject = function (object) {
    for (var i = 0; i < this.length; i++) {
        if (JSON.stringify(this[i]) === JSON.stringify(object))
            return i;
    }
}

你可以简单地使用

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,只有一个略读。

我比较了几种方法,得到了一个最快解决这个问题的结果。这是一个for循环。它比其他方法快5倍以上。

下面是测试页面:https://jsbench.me/9hjewv6a98

这是在数组中查找对象索引的方法

    var myArray = [{  hello: 'world',
        foo: 'bar'
    },{
        hello: 'stevie',
        foo: 'baz'
    }];



    for (i = 0; i < myArray.length; i++) {
        if (myArray[i].hello === 'stevie') {
            alert('position: ' + i);
            return;
        }
    }