Javascript – indexOf method in an object array

javascript

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.

Best Answer

I think you can solve it in one line using the map function:

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