开发者

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


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


With this:

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

Cheers


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜