繁体   English   中英

如何使用Javascript搜索特定的JSON键值对?

[英]How do I search for a specific JSON key value pair using Javascript?

我目前正在构建一个应用程序,该应用程序可以告诉您指定城市中即将发生的事件的天气。我使用了两个API,一个返回的对象数组对应于插入文本输入中的艺术家的每个事件,另一个返回输入另一个输入的城市的天气。

我正在使用.getJSON方法来检索数据。 当前,艺术家API返回所有输入的艺术家即将发生的事件,并且我想搜索事件对象以找到与位置字段的输入相匹配的键“城市”(该位置从天气API中加载数据)。 。

var bandData;
var locationData;

$(document).ready(function() {
    $("#get-weather").click(function(e){
        e.preventDefault();
        //prevent empty fields
       if($.trim($('#artist-search').val()) == ''){
          $(".error").css("display", "block").html("input cannot be left 
blank");
       } else {
            $(".error").css("display", "none");
            //artist field
            var artistField = $("#artist-search").val();

$.getJSON("https://rest.bandsintown.com/artists/"+artistField+"/events?
app_id="+bandKey, function(response){
            console.log(response);
            bandData = response;
});
        //location field
        var locationField = $("#location").val();
        $.getJSON("http://api.openweathermap.org/data/2.5/weather?q="+locationField+",us&units=imperial&APPID="+weatherKey, 
        function(data){
            console.log(data);
            locationData = data;
        });
        };

    });
});

JSON:

{
"id": "21023151",
"artist_id": "7931668",
"url": "https://www.bandsintown.com/e/URLinfo",
"on_sale_datetime": "",
"datetime": "2018-04-14T12:00:00",
"description":"",
"venue": {
  "name": "Coachella Music and Arts Festival",
  "latitude": "33.680015",
  "longitude": "-116.23722",
  "city": "Indio",
  "region": "CA",
  "country": "United States"
},
"offers": [
        {
    "type": "Tickets",
    "url": "https://www.bandsintown.com/t/URLinfo",
    "status": "available"
  }
                    ],
"lineup": [
                "Post Malone"
                ]
  }

我该怎么做才能根据用户输入的城市来过滤JSON数据? 并且,如果未返回任何内容,则打印“无结果”之类的内容。 当前,当我console.log“ bandData”和“ locationData”时,我得到一个未定义的值。

您可以通过地图/过滤器执行以下操作

var locationField = $("#location").val();
       $.getJSON("http://api.openweathermap.org/data/2.5/weather?q="+locationField+",us&units=imperial&APPID="+weatherKey, 
                 function(data){
                    var FilteredData = data.filter(fundtion(elem){return (elem.venue.city == locationField) });
                      if(FilteredData.length){
                          console.log(FilteredData );
                          locationData = FilteredData ;
                      }
                      else{
                          console.log("No Data");
                      }
                  });
         };

如果添加一些错误处理(如空检查等),那将永远是件好事。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM