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

时间:2022-09-25 09:14:46

How can I search in an array to see if the value exists?

如何在数组中搜索以查看值是否存在?

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

So far I tried .is , .has , .getdata and .inarray, but it's getting me nowhere.

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

The JSON call returns: [{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]

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

2 个解决方案

#1


24  

I think its a syntax error: Change if ($(array.has("special item"))){ to

我认为这是一个语法错误:更改if($(array.has(“special item”))){to

if ($.inArray("special item", array) > -1){ 

EDIT:

编辑:

If the array has complex objects then you cannot use inArray, instead you can use the jQuery filter to achieve the same, e.g:

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

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

#2


2  

if ( $.inArray(valueToMatch, theArray) > -1 ) 

#1


24  

I think its a syntax error: Change if ($(array.has("special item"))){ to

我认为这是一个语法错误:更改if($(array.has(“special item”))){to

if ($.inArray("special item", array) > -1){ 

EDIT:

编辑:

If the array has complex objects then you cannot use inArray, instead you can use the jQuery filter to achieve the same, e.g:

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

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

#2


2  

if ( $.inArray(valueToMatch, theArray) > -1 )