weixin_33691598 2014-06-27 22:42 采纳率: 0%
浏览 7

在json数组中搜索值

I have a json array of values that is dynamically populated and returned via an ajax call. This json data can contain any number of objects. For example, my ajax call returned an array of gems ['ruby', 'emerald', 'topaz'].

On my html page I have a text input somewhere on the page where a user can add a new gem. When the user adds a gem (via a button click), I want to see if it already exists in my json array. So if user enters 'diamond' then ultimately a check box should get checked.

My code:

  function AddGem(data){ //data is the dynamically populated data from my ajax call

                var gem = $("#Gem").val(); // this the text input value of the textbox where a user can enter a gem. I am checking the json array values against this value
                $("#Button").click(function() { //user clicks a button to add a gem to the input textbox
                    $.each(data, function (item) {
                        if(item === 'gem')
                        {
                            $("#Oldform").prop("checked", false); // leave checkbox unchecked
                        } else
                            {
                                $("#Oldform").prop("checked", true); //check check box
                            }   
                        });
                      });  
                    }

How can I execute the search of my json array? Do I need to create an empty array first ie. data = [];? Thanks,

  • 写回答

2条回答 默认 最新

  • csdnceshi62 2014-06-27 22:54
    关注

    I think you wanted to use gem variable instead of 'gem' string.

    Something like:

    $("#Button").click(function() {
        $.each(data, function (item) {
            $("#Oldform").prop("checked", item === gem);
        });  
    });
    

    But consider using indexOf:

    $("#Button").click(function() {
        $("#Oldform").prop("checked", data.indexOf(gem)>-1);
    });
    
    评论

报告相同问题?