简体   繁体   中英

How do I iterate over a JSON array

I'm loading the following json file from a url:

{
    "Airports": [
      {
        "listing": "East 34th Street Heliport",
        "iata": "TSS",
        "type": "heliport",
        "size": "tiny"
      },
      {
        "listing": "Blaine Municipal Airport",
        "iata": "BWS",
        "type": "closed",
        "size": "small"
      },
      {
        "listing": "Toronto City Airport",
        "iata": "YTZ",
        "type": "airport",
        "size": "medium"      
      },
      {
        "listing": "Amsterdam Airport Schiphol",
    "iata": "AMS",
        "type": "airport",
        "size": "large"      
       },
      {
        "listing": "Detroit County Airport",
        "iata": "DTW",
        "type": "airport",
        "size": "large"
      }
    ]
}

And I want to go through the Airports array and display all key names and values on the DOM. I do this in a .each() loop using jquery mobile :

    if(pageID == "page1"){
        var pageTitle="Error";
        //temp var to hold collapsible HTML 
        var colItem="";

        $.ajax({
        url:"some_url",
        method:"GET",
        cache:false,
        dataType:"json",
        success:function(data){

            pageTitle = (Object.keys(data)[0]).toUpperCase();


            $(data.Airports).each(function(index,value){                   

                //build all the needed collapsibles
                colItem += 
                        "<div data-role='collapsible'><h2>" 
                        + value.listing + 
                        "</h2> <p>" 
                        + + 
                        "</p> <p>" 
                        + + 
                        "</p> <p>" 
                        + + 
                        "</p></div>";

            });
        }            

    });

Is there a way to do this without referencing the key values such as what I have done using value.listing but instead iterate through it like an array an get all the values that way.

I'm looking for a final result similar to this:

 East 34th Street Heliport

iata       TSS
type       heliport
size       tiny

You can do this way. Create HTML string dynamically and then add that to the main HTML page:

 var jsonData = { "Airports": [ { "listing": "East 34th Street Heliport", "iata": "TSS", "type": "heliport", "size": "tiny" }, { "listing": "Blaine Municipal Airport", "iata": "BWS", "type": "closed", "size": "small" }, { "listing": "Toronto City Airport", "iata": "YTZ", "type": "airport", "size": "medium" }, { "listing": "Amsterdam Airport Schiphol", "iata": "AMS", "type": "airport", "size": "large" }, { "listing": "Detroit County Airport", "iata": "DTW", "type": "airport", "size": "large" } ] }; var nHTML = ''; jsonData.Airports.forEach(function(airport){ var paragraph = ''; paragraph+='<p>iata: '+airport.iata+'</p>' + '<p>type: '+airport.type+'</p>' + '<p>size: '+airport.size+'</p>'; var colItem = '<div data-role="collapsible">' +airport.listing+ '<h2></h2>'+paragraph+'</div>'; nHTML+=colItem; }); $('#container').html(nHTML); 
 #container div{ margin: 7px; background: grey; padding: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='container'></div> 

Here's a very simple JSFiddle of how you can do it:

https://jsfiddle.net/8euuoccf/

var jsonData = {
  "Airports": [{
      "listing": "East 34th Street Heliport",
      "iata": "TSS",
      "type": "heliport",
      "size": "tiny"
    },
    {
      "listing": "Blaine Municipal Airport",
      "iata": "BWS",
      "type": "closed",
      "size": "small"
    },
    {
      "listing": "Toronto City Airport",
      "iata": "YTZ",
      "type": "airport",
      "size": "medium"
    },
    {
      "listing": "Amsterdam Airport Schiphol",
      "iata": "AMS",
      "type": "airport",
      "size": "large"
    },
    {
      "listing": "Detroit County Airport",
      "iata": "DTW",
      "type": "airport",
      "size": "large"
    }
  ]
};

$(document).ready(function() {

    // Iterate over each airport
    jsonData.Airports.forEach(airport => {
      colItem = `<div data-role='collapsible'><h2>${airport.listing}</h2>`;

      // Iterate over each airport key
      Object.keys(airport).forEach(key => {
        colItem += `<p>${key}: ${airport[key]}</p>`;
      });
      colItem += '</div>';

      // Finally, append it to body
      var html = $.parseHTML(colItem);
      $('body').append(colItem);
    });
});

There are several ways to iterate over Object keys/values. Object.entries() is another option, but bear in mind it's not supported in IE. In this example I've used Object.keys() and then I access the corresponding value. If you want it in another format in the DOM (such as a table), take key and airport[key] and append them however you prefer.

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