Search Index of the array from the json value using indexOf

4

I have the following array:

var usuarios = [
    {nome: "João", id: 1},
    {nome: "Maria", id: 2},
    {nome: "José", id: 3},
    {nome: "Ana", id: 4},
];

I need to return the user index José. I tried using indexOf as follows:

var usuarios = [
        {nome: "João", id: 1},
        {nome: "Maria", id: 2},
        {nome: "José", id: 3},
        {nome: "Ana", id: 4},
    ];
  
  console.log(usuarios.indexOf({nome: "José", id: 3}))

But it is returned -1. I know it's possible to do this with for (), but is it possible to do with indexOf?

    
asked by anonymous 16.06.2016 / 02:12

1 answer

3

Your logic fails because objects are unique, unless they refer to each other.

Notice these examples:

var a = {};
var b = {};
console.log(a == b); // false

var a = {};
var b = a;
console.log(a == b); // true

So when you use indexOf it will search the array for a == element and will always give false.

You could make an approximation, but that is not reliable like this:

var u = usuarios.map(JSON.stringify);
console.log(u.indexOf('{"nome":"José","id":3}')); // dá 2

But in this case you compare strings and lose the advantage of using objects. As you suggested the best is with cycle for and with break or return so you do not need to reach the end, but even there you have to compare values and not the object itself (except as stated above that you have a reference in a variable):

function getId(nome) {
    for (var i = 0; i < usuarios.length; i++) {
        if (usuarios[i].nome == nome) return i;
    }
}

console.log(getId('José')); // dá 2

jsFiddle: link

    
16.06.2016 / 02:28