Check for JSON value in JavaScript array

I have an array of JSON objects, for example:

var myArray = [ {name:'foo',number:2}, {name:'bar',number:9}, {etc.} ] 

How to determine if myArray contains an object with name = "foo"?

+7
source share
4 answers

If I am missing something, you should use them, at least for readability, and not for the map. And for performance, you have to break every time you find what you are looking for, there is no reason to continue the cycle:

 var hasFoo = false; $.each(myArray, function(i,obj) { if (obj.name === 'foo') { hasFoo = true; return false;} }); 
+7
source
 for(var i = 0; i < myArray.length; i++) { if (myArray[i].name == 'foo') alert('success!') } 
+1
source

Wherein:

 $.each(myArray, function(i, obj){ if(obj.name =='foo') alert("Index "+i + " has foo"); }); 

Greetings

+1
source
 var hasFoo = false; $.map(myArray, function(v) { if (v.name === 'foo') { hasFoo = true; } }); 
0
source

All Articles