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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7262513/
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-08-26 23:37:43  来源:igfitidea点击:

How to find object value in array with Jquery?

jqueryarraysjson

提问by Jroen

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, .getdataand .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"}]

回答by Chandu

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

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

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){

回答by aziz punjani

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