【问题标题】:How to find object value in array with Jquery?如何使用 Jquery 在数组中查找对象值?
【发布时间】:2011-11-07 22:00:24
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你的阵列是什么样子的?

标签: jquery arrays json


【解决方案1】:

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

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

编辑:

如果数组有复杂的对象,那么你不能使用inArray,你可以使用jQuery过滤器来实现同样的效果,例如:

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

【讨论】:

  • 虽然答案在这里显示了两次,但这似乎不起作用。
  • 你能发布 JSON 调用返回的数组吗?
  • JSON 调用返回:[{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]
  • @Jroen:更新帖子请检查。
【解决方案2】:
if ( $.inArray(valueToMatch, theArray) > -1 ) 

【讨论】:

    猜你喜欢
    • 2023-01-22
    • 2012-09-06
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2022-11-04
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多