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.