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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分