indexOf method in an object array?

2018-12-31 07:28发布

What's the best method to get the index of an array which contains objects?

Imagine this scenario:

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

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

Now I would like to have the indexOf the object which hello property is 'stevie' which, in this example, would be 1.

I'm pretty newbie with JavaScript and I don't know if there is a simple method or if I should build my own function to do that.

标签: javascript
27条回答
有味是清欢
2楼-- · 2018-12-31 07:43

Use _.findIndex from underscore.js library

Here's the example _.findIndex([{a:1},{a: 2,c:10},{a: 3}], {a:2,c:10}) //1

查看更多
裙下三千臣
3楼-- · 2018-12-31 07:45
var idx = myArray.reduce( function( cur, val, index ){

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

}, -1 );
查看更多
临风纵饮
4楼-- · 2018-12-31 07:46

If you are only interested into finding the position see @Pablo's answer.

pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');

However, if you are looking forward to finding the element (i.e. if you were thinking of doing something like this myArray[pos]), there is a more efficient one-line way to do it, using filter.

element = myArray.filter((e) => e.hello === 'stevie')[0];

See perfomance results (~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3

查看更多
时光乱了年华
5楼-- · 2018-12-31 07:48

This is the way to find the object's index in array

    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;
        }
    }
查看更多
低头抚发
6楼-- · 2018-12-31 07:48
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"));
查看更多
长期被迫恋爱
7楼-- · 2018-12-31 07:50

Array.prototype.findIndex is supported in all browsers other than IE (non-edge). But the polyfill provided is nice.

var indexOfStevie = myArray.findIndex(i => i.hello === "stevie");

The solution with map is okay. But you are iterating over the entire array every search. That is only the worst case for findIndex which stops iterating once a match is found.


There's not really a concise way (when devs had to worry about IE8), but here's a common solution:

var searchTerm = "stevie",
    index = -1;
for(var i = 0, len = myArray.length; i < len; i++) {
    if (myArray[i].hello === searchTerm) {
        index = i;
        break;
    }
}

or as a function:

function arrayObjectIndexOf(myArray, searchTerm, property) {
    for(var i = 0, len = myArray.length; i < len; i++) {
        if (myArray[i][property] === searchTerm) return i;
    }
    return -1;
}
arrayObjectIndexOf(arr, "stevie", "hello"); // 1

Just some notes:

  1. Don't use for...in loops on arrays
  2. Be sure to break out of the loop or return out of the function once you've found your "needle"
  3. Be careful with object equality

For example,

var a = {obj: 0};
var b = [a];
b.indexOf({obj: 0}); // -1 not found
查看更多
登录 后发表回答