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

例如,给定这个输入:

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

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

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


当前回答

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

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

其他回答

我喜欢Pablo的回答,但是array# indexOf和array# map并不适用于所有浏览器。下划线将使用本机代码,如果它是可用的,但也有回退。另外,它有pluck方法来做Pablo的匿名映射方法所做的事情。

var idx = _.chain(myArray).pluck("hello").indexOf("Stevie").value();

这无需自定义代码即可实现

var arr, a, found;
arr = [{x: 1, y: 2}];
a = {x: 1, y: 2};
found = JSON.stringify(arr).indexOf(JSON.stringify(a)) > - 1;
// found === true

注意:这并没有给出实际的索引,它只告诉你的对象是否存在于当前的数据结构中

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

喜欢的东西:

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

你可以使用一个本地方便的函数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);

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

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