简体   繁体   English

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

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

I'm currently building an app that tells you the weather for an upcoming event in a city you specify.. I'm using two APIs, one returns an array of objects that correspond to each event by an artist inserted into a text input, and the other returns the weather for a city entered into another input. 我目前正在构建一个应用程序,该应用程序可以告诉您指定城市中即将发生的事件的天气。我使用了两个API,一个返回的对象数组对应于插入文本输入中的艺术家的每个事件,另一个返回输入另一个输入的城市的天气。

I'm using .getJSON method to retrieve the data. 我正在使用.getJSON方法来检索数据。 Currently the artist API returns all of the entered artists' upcoming events, and I want to search through the event objects to find a key "city" that matches the input of the location field (which loads the data from the weather API)... 当前,艺术家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: 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"
                ]
  }

What can I do to filter the JSON data by what city the user types in? 我该怎么做才能根据用户输入的城市来过滤JSON数据? And, if nothing is returned, print something like "no results". 并且,如果未返回任何内容,则打印“无结果”之类的内容。 Currently when I console.log "bandData" and "locationData" I get an undefined value. 当前,当我console.log“ bandData”和“ locationData”时,我得到一个未定义的值。

You can do this through map/filter as follows 您可以通过地图/过滤器执行以下操作

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

It will be always good if you add some error handling such null check, etc. 如果添加一些错误处理(如空检查等),那将永远是件好事。

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

相关问题 如何在ajax javascript中获取数据类型json的特定值键对? - How do I get specific value key pair in ajax javascript for datatype json? 如何在jquery / javascript中的键/值数组中的特定点插入键值对? - How do I insert a key value pair at a specific point in a key/value array in jquery/javascript? 在Javascript中,如何检查嵌套在另一个键/值对中的特定键/值对的存在? - In Javascript, how can I check the existence of a specific key/value pair nested inside another key/value pair? 如何在JavaScript中使用正则表达式搜索键/值对? - How to search a key/value pair with a regex in JavaScript? 如何查询包含特定键/值对的文档 - How do I query for documents that contain a specific key/value pair 如何在不知道使用JSON的javascript中特定键的情况下获取属性值 - How do I get property value without knowing it's specific key in javascript using JSON 如何将键值对与Json字符串分开 - How do I separate key value pair from Json String 如何将 JSON 值转换为键值对 pir - How do I convert JSON values into a key value pair pir 如何在javascript中的顺序中添加key:value对 - How do I add key:value pair in an order in javascript 如何将键值对添加到 javascript 中的关联数组 - How do i add a key value pair to an asociative array in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM