If you have an object reference, you can use the indexOf
same, which strives for equality (two references are equal only 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 your 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 even (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.
Don’t forget to use
var
sounded like a subliminal message to me– Wallace Maxters
That was the idea :)
– bfavaretto