How do I search for a particular object within an array?

7

I need to know if given Array has objeto with a certain value in its index.

I tried to use indexOf , but I was not successful.

arr = [];

arr.push({id: 1, nome: 'Wallace'});

arr.indexOf({id: 1}); // -1

How can I do to search for this object only by the specific index (in this case, id )?

    
asked by anonymous 31.07.2015 / 16:05

5 answers

8

If you have an object reference, you can use indexOf itself, which does search for equality (two references are only equal if they point to the same object):

// Não se esqueça de usar var!
var arr = [];
var obj1 = {id: 1, nome: 'Wallace'}
arr.push(obj1);
arr.indexOf(obj1);

Otherwise, you need to check everything in the array until you find its object:

var arr = [];
arr.push({id: 1, nome: 'Wallace'});
for(var i=0; i<arr.length; i++) {
    if(arr[i].id === 1) {
        // achou!
    }
}

or (IE9 +):

var arr = [];
arr.push({id: 1, nome: 'Wallace'});
arr.forEach(function(el, i){
    if(el.id === 1) {
        // achou!
    }
});

or (IE9 +):

var arr = [];
arr.push({id: 1, nome: 'Wallace'});
var existe = arr.some(function(el, i){
    return el.id === 1;
});

These are just some of the possible methods. In the other answers you will see that you can also do with filter , map , among other methods.     

31.07.2015 / 16:14
3

Why did not arr.indexOf({id: 1}); work?

The problem is that when you do arr.indexOf({id: 1}); you are creating a new object and not creating a twin / equal of the other that is already inside the array.

Notice that in JavaScript this gives false:

var a = {id: 1};
var b = {id: 1};
a == b // false

You have to use something that iterates through this array. For example .filter() .

Instead of looking for object I suggest using an array, or two parameters. Something like this:

function verificar(arr, procurar) {
    var chave = procurar[0];
    var valor = procurar[1];
    return !!arr.filter(function (el) {
        return el[chave] == valor;
    }).length;
}

jsFiddle: link

    
31.07.2015 / 16:13
3

Hello,

You would do this as follows

function procurarIndice(arraySearch, atributo, valor){
   var cont=0;
   var indices=[];
   for(var i in arraySearch){
      var row = arraySearch[i];
      if(row[atributo]==valor){
         indices.push(cont)
      }
      cont++;
   }
   return indices;
}
arr = [];
arr.push({id: 1, nome: 'Wallace'});

procurarIndice(arr,"id",1);

The function would return an array of indexes, and to validate if the expected value exists, you could use an if by

if(procurarIndice(arr,"id",1).length>0){
   ...
}
    
31.07.2015 / 16:24
3

Another solution is to use the .map (source :) method link )

The map() method invokes the callback function passed by argument for each element of Array and returns a new Array as a result.

var log = document.getElementById("menssagemLog");

arr = [];

arr.push({id: 1, nome: 'Wallace'});
arr.push({id: 2, nome: 'Carlos'});
arr.push({id: 3, nome: 'Livia'});

pos = arr.map(function(e) { return e.id; });
log.innerHTML += pos.indexOf(0)// Retorna -1
log.innerHTML += "<br/>"+pos.indexOf(1); // Retorna 0
log.innerHTML += "<br/>"+pos.indexOf(2); // Retorna 1
log.innerHTML += "<br/>"+pos.indexOf(4); // Retorna -1

console.log(log.innerHTML)
<div id="menssagemLog"></div>
    
31.07.2015 / 16:19
-1
var arr = [{id:1, desc:"1111"},{id:2, desc:"222"},{id:3, desc:"3333"},{id:4, desc:"4444"}];

arr.filter(function( obj ) {
  return obj.id == 1;
});
    
25.04.2017 / 02:47