Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 902
thugsb Avatar asked May 06 '11 22:05

thugsb


1 Answers

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;}
});  
like image 62
James Montagne Avatar answered Oct 12 '22 23:10

James Montagne