7

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

1

4 Answers 4

8

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;}
});  
Sign up to request clarification or add additional context in comments.

Comments

1

With this:

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

Cheers

1 Comment

Array.prototype.each does not exists. Either you mean $.each from jQuery or Array.prototype.forEach which is only supported by newer browsers.
1
for(var i = 0; i < myArray.length; i++) { 
   if (myArray[i].name == 'foo') 
        alert('success!') 
 }

1 Comment

Don't use for...in to loop over an array.
0
var hasFoo = false;
$.map(myArray, function(v) {
  if (v.name === 'foo') { hasFoo = true; }
});

4 Comments

curious, why map instead of each?
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.
won't somebody think of the poor orphans!
The disadvantage is that you can not terminate the looping earlier (as opposed to each).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.