如何使用Jquery在数组中查找对象值?

前端之家收集整理的这篇文章主要介绍了如何使用Jquery在数组中查找对象值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在数组中搜索以查看值是否存在?
  1. var fruitVarietyChecked = $('input[name=fruitVariety]:checked').val();
  2.  
  3. $.getJSON('getdata.PHP',{fruitVariety: fruitVarietyChecked},function(fruittype) {
  4.  
  5. var html = '';
  6. $.each(fruittype,function(index,array) {
  7.  
  8. alert( "Key: " + index + ",Value: " + array['fruittype'] );
  9. //shows array - Key: 0,Value: special item
  10.  
  11. //this is where the problem is
  12. if ($(array.has("special item"))){
  13.  
  14. $("p").text("special item" + " found at " + index);
  15. return false;
  16. }
  17.  
  18. html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
  19. });
  20. $('#fruittype').html(html);
  21. });
  22. }

到目前为止,我尝试过.is,.has,.getdata和.inarray,但它让我无处可去.

JSON调用返回:[{“fruittype”:“special item”},{“fruittype”:“blue”},{“fruittype”:“red”}]

解决方法

我认为这是一个语法错误
更改if($(array.has(“special item”))){
  1. if ($.inArray("special item",array) > -1){

编辑:

如果数组有复杂的对象,那么就不能使用inArray,而是可以使用jQuery过滤器来实现相同的目的,例如:

  1. var filtered = $(array).filter(function(){
  2. return this.fruittype == "special item";
  3. });
  4. if(filtered.length > 0){

猜你在找的jQuery相关文章