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!') 
 }
Share:
16,788
thugsb
Author by

thugsb

Updated on June 28, 2022

Comments

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

  • James Montagne
    James Montagne about 13 years
    curious, why map instead of each?
  • Felix Kling
    Felix Kling about 13 years
    Don't use for...in to loop over an array.
  • Felix Kling
    Felix Kling about 13 years
    Array.prototype.each does not exists. Either you mean $.each from jQuery or Array.prototype.forEach which is only supported by newer browsers.
  • mVChr
    mVChr about 13 years
    I 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
    James Montagne about 13 years
    won't somebody think of the poor orphans!
  • Felix Kling
    Felix Kling about 13 years
    The disadvantage is that you can not terminate the looping earlier (as opposed to each).