Daniel Fernandez Daniel Fernandez - 1 year ago 147
Javascript Question

Index of javascript object in array of objects

I have an array of objects in javascript, something like

var arrayobj = [{a:'a'},{b:'b'},{c:'c'}]
(but with more complex values).

Now I check the index of some object manually, like

And I got
Object {b: "b"}

Now I type

and the response is
(aka not found).

Anyone could tell me why this happens? I have read the documentation on indexOf method and arrays, but I still have no clue.

Thanks in advance!

Answer Source

indexOf checks for equality (specifically strict equality, ===, but it doesn't matter for this question). Two different objects are not equal to each other even if they have the same properties. The object in your array and the one you pass to indexOf are different objects, and so they don't match.

If you searched for the same object, it would find it:

var b = {b:'b'};
var arrayobj = [{a:'a'},b,{c:'c'}];
console.log(arrayobj.indexOf(b)); // 1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download