Jro*_*oen 8 arrays jquery json
如何在数组中搜索以查看该值是否存在?
var fruitVarietyChecked = $('input[name=fruitVariety]:checked').val();
$.getJSON('getdata.php', {fruitVariety: fruitVarietyChecked}, function(fruittype) {
var html = '';
$.each(fruittype, function(index, array) {
alert( "Key: " + index + ", Value: " + array['fruittype'] );
//shows array - Key: 0 , Value: special item
//this is where the problem is
if ($(array.has("special item"))){
$("p").text("special item" + " found at " + index);
return false;
}
html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我试过.is,.has,.getdata和.inarray,但它让我无处.
JSON调用返回: [{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]
Cha*_*ndu 24
我认为它的语法错误:if ($(array.has("special item"))){
改为
if ($.inArray("special item", array) > -1){
Run Code Online (Sandbox Code Playgroud)
编辑:
如果数组有复杂的对象,那么就不能使用inArray,而是可以使用jQuery过滤器来实现相同的目的,例如:
var filtered = $(array).filter(function(){
return this.fruittype == "special item";
});
if(filtered.length > 0){
Run Code Online (Sandbox Code Playgroud)