Test existence of JSON value in JavaScript Array
16,788
Solution 1
Unless I'm missing something, you should use each at the very least for readability instead of map. And for performance, you should break the each once you've found what you're looking for, no reason to keep looping:
var hasFoo = false;
$.each(myArray, function(i,obj) {
if (obj.name === 'foo') { hasFoo = true; return false;}
});
Solution 2
With this:
$.each(myArray, function(i, obj){
if(obj.name =='foo')
alert("Index "+i + " has foo");
});
Cheers
Solution 3
for(var i = 0; i < myArray.length; i++) {
if (myArray[i].name == 'foo')
alert('success!')
}
Author by
thugsb
Updated on June 28, 2022Comments
-
thugsb almost 2 years
I have an array of JSON objects like so:
var myArray = [ {name:'foo',number:2}, {name:'bar',number:9}, {etc.} ]
How do I detect if myArray contains an object with name="foo"?
-
Quentin about 13 years
-
-
James Montagne about 13 yearscurious, why map instead of each?
-
Felix Kling about 13 yearsDon't use
for...in
to loop over an array. -
Felix Kling about 13 years
Array.prototype.each
does not exists. Either you mean$.each
from jQuery orArray.prototype.forEach
which is only supported by newer browsers. -
mVChr about 13 yearsI just happened to be messing around with the new jQuery 1.6 map on objects and so this was the first thing that came to mind. Can't imagine there's a performance difference, just need to get over the sorrow of return values being lost to the ether.
-
James Montagne about 13 yearswon't somebody think of the poor orphans!
-
Felix Kling about 13 yearsThe disadvantage is that you can not terminate the looping earlier (as opposed to
each
).