简体   繁体   中英

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.

I'm using .getJSON method to retrieve the data. 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)...

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"
                ]
  }

What can I do to filter the JSON data by what city the user types in? And, if nothing is returned, print something like "no results". Currently when I console.log "bandData" and "locationData" I get an undefined value.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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