thugsb
thugsb

Reputation: 23426

Test existence of JSON value in JavaScript Array

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"?

Upvotes: 7

Views: 16884

Answers (4)

Marek
Marek

Reputation: 1788

for(var i = 0; i < myArray.length; i++) { 
   if (myArray[i].name == 'foo') 
        alert('success!') 
 }

Upvotes: 1

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

With this:

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

Cheers

Upvotes: 1

James Montagne
James Montagne

Reputation: 78640

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;}
});  

Upvotes: 8

mVChr
mVChr

Reputation: 50177

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

Upvotes: 0

Related Questions