【问题标题】:How do I iterate over a JSON array如何遍历 JSON 数组
【发布时间】:2018-10-05 09:32:48
【问题描述】:

我正在从一个 url 加载以下 json 文件:

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

我想遍历 Airports 数组并在 DOM 上显示所有键名和值。我使用 jquery mobile 在 .each() 循环中执行此操作:

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

            });
        }            

    });

有没有一种方法可以在不引用键值的情况下执行此操作,例如我使用 value.listing 所做的,而是像数组一样遍历它并以这种方式获取所有值。

我正在寻找类似这样的最终结果:

 East 34th Street Heliport

iata       TSS
type       heliport
size       tiny

【问题讨论】:

    标签: arrays json html jquery-mobile


    【解决方案1】:

    你可以这样做。动态创建 HTML 字符串,然后将其添加到 HTML 主页面:

    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>

    【讨论】:

    • 要求iata、type、size等键名是从json文件中加载出来的,不能硬编码进去。也不能引用airport.iata等键名使用循环调用这些值来遍历并调用所有键名。有些喜欢。 var keyNames = Object.keys(airport) 而不是使用 keyNames 来调用 keyValues。
    【解决方案2】:

    这是一个非常简单的 JSFiddle,说明如何做到这一点:

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

    有几种方法可以迭代对象键/值。 Object.entries() 是另一种选择,但请记住,IE 不支持它。在这个例子中,我使用了Object.keys(),然后我访问了相应的值。如果您希望它在 DOM 中以另一种格式(例如表格),请使用 keyairport[key] 并按照您的喜好附加它们。

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 2021-04-26
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多