测试 JavaScript 数组中 JSON 值是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5917480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:47:09  来源:igfitidea点击:

Test existence of JSON value in JavaScript Array

javascriptjqueryarraysjson

提问by thugsb

I have an array of JSON objects like so:

我有一个像这样的 JSON 对象数组:

var myArray = [
  {name:'foo',number:2},
  {name:'bar',number:9},
  {etc.}
]

How do I detect if myArray contains an object with name="foo"?

如何检测 myArray 是否包含 name="foo" 的对象?

回答by James Montagne

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:

除非我遗漏了某些东西,否则您至少应该使用每个来提高可读性而不是地图。对于性能,一旦找到要查找的内容,就应该打破 each ,没有理由继续循环:

var hasFoo = false;
$.each(myArray, function(i,obj) {
  if (obj.name === 'foo') { hasFoo = true; return false;}
});  

回答by Marek

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

回答by Edgar Villegas Alvarado

With this:

有了这个:

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

Cheers

干杯

回答by mVChr

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