draxu26480 2016-12-10 05:09
浏览 113
已采纳

访问嵌套的json对象

I am trying to access JSON objects in JavaScript and display them in HTML table, I managed to do it but failed to display one of the columns.

project link

<script>
        var arrItems = [];      // THE ARRAY TO STORE JSON ITEMS.
        $.each(data.glance, function (index, value) {
            arrItems.push(value);       // PUSH THE VALUES INSIDE THE ARRAY.


        // EXTRACT VALUE FOR TABLE HEADER.
        var col = [];
        for (var i = 0; i < arrItems.length; i++) {
            for (var key in arrItems[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < arrItems.length; i++) {

            tr = table.insertRow(-1);
            data
            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = arrItems[0];
                tabCell.innerHTML = arrItems[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("daytoday");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    });

Also, am trying to access images and display them in slider but not sure how to access the nested image object,

Question: Can someone show me how can I access the images?

Image slider page

 <script>

$('img[class="logo"]').attr('src',data.logo);
$('div[class="header_bg"]').css('background-image', 'url(' + data.topbanner + ')');
//alert(JSON.stringify(data.property_images));
var countDown=0;
$.each(data.property_information,function(key,value){
  if(key!='NGORONGORO SOPA LODGE'){
  //alert(key);
    var cont="";
    var innerDivTop ='<div class="centre-container">'
                        +'<div  class="page-content">'
                        +'<div class="flex">'
                         +'<div class="body" style="width: 100%;">'
                          +'<div class="content-block"><h2 style="font-weight:bold">'+key+'</h2>'
                           +'<div class="flexslider">'
                              +'<div class="arrow-next" data-role="'+countDown+'"></div>'
                               +'<div class="arrow-back" data-role="'+countDown+'"></div>'
                                +'<ul class="services dynmic_'+countDown+'" >';



    for(var i=0;i<value.length;i++) {

      if(i==0) {
       // alert(value[i]);
       // console.log(value[i]);

       cont +='<li style="display: block;"><img src="'+value[i]+'" alt="" style="width:1088px;height:430px;" ></li>';

      } else {
        cont +='<li><img src="'+value[i]+'" alt="" style="width:1088px;height:430px;"></li>';

      } 
    }

        var innerDivBot='</ul>'
                          +'</div></div></div></div></div></div>';
 $('#contentRpt').append(innerDivTop+cont+innerDivBot);
 countDown +=1;
 }
});

Here is my Json data example :

 { "glance": {
"Day 1": {
  "location": "ARUSHA",
  "property": "THE ARUSHA HOTEL"
},
"Day 2": {
  "location": "TARANGIRE NATIONAL PARK",
  "property": "TARANGIRE SAFARI LODGE"
},
"Day 3": {
  "location": "LAKE MANYARA NATIONAL PARK",
  "property": "LAKE MANYARA HOTEL"
},
"Day 4": {
  "location": "SERENGETI NATIONAL PARK",
  "property": "SERENGETI SOPA LODGE"
},
"Day 5": {
  "location": "SERENGETI NATIONAL PARK",
  "property": "SERENGETI SOPA LODGE"
},
"Day 6": {
  "location": "SERENGETI NATIONAL PARK",
  "property": "SERENGETI SOPA LODGE"
},
"Day 7": {
  "location": "NGORONGORO CONSERVATION AREA AUTHORITY",
  "property": "NGORONGORO SOPA LODGE"
}
 }, "property_information": {
"THE ARUSHA HOTEL": {
  "description": "Arusha\u2019s supreme boutique hotel offering first class accommodation and service, surrounded by the history of bygone eras. The hotel boasts the finest location in the heart of Arusha, in the tranquil surroundings of its own tropical gardens.

The Arusha Hotel boasts 86 elegantly appointed rooms included 4 Suites, 25 Executive Deluxe rooms and 57 Superior Rooms. Professionally managed, we ensure the needs of every guest are carried out with East African charm and warmth.

",
  "images": [
    "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/the_arusha_hotel\/dining_parachichi.jpg",
    "http:\/\/asktechtzco.tz\/spear22\/\/images\/demo\/accommodation\/the_arusha_hotel\/images-30.jpeg",
    "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/the_arusha_hotel\/room_superior1.jpg"
  ]
},
"TARANGIRE SAFARI LODGE": {
  "description": "Built on top of a high bluff with a breathtaking panorama, our lodge is superbly located in Tarangire National Park, providing one of the best views in Africa.

Carving out the landscape below the lodge is Tarangire River, a favourite watering place, which attracts impressive numbers and variety of game. The scene unfolds before you while lounging on the outdoor patio, allowing you to appreciate Tarangire\\\\\\\\\\\\\\&#039;s diverse wildlife without ever leaving the lodge.",
  "images": [
    "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/tarangire_safari_lodge\/images-31.jpeg",
    "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/tarangire_safari_lodge\/images-32.jpeg",
    "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/tarangire_safari_lodge\/images-33.jpeg"
  ]
}

}}

  • 写回答

1条回答 默认 最新

  • dongyi7513 2016-12-10 06:17
    关注

    You are trying to show a property name so you a nested loop here first to access object property and its value and then a second loop to extract values from value you extract in outer loop.

    Try like this

    $(function() {
      table = $("<table></table>").appendTo("#daytoday");
      table.append("<tr><th>DAY</th><th> LOCATION </th><th> HOTEL </th></tr>")
      $.each(data.glance, function(index, value) {
        row = $("<tr></tr>").appendTo(table);
        $("<td></td>").appendTo(row).html(index);
    
        $.each(value, function(i, v) {
          $("<td></td>").appendTo(row).html(v);
        });
      });
    
    });
    

    var data = {
      "glance": {
        "Day 1": {
          "location": "ARUSHA",
          "property": "THE ARUSHA HOTEL"
        },
        "Day 2": {
          "location": "TARANGIRE NATIONAL PARK",
          "property": "TARANGIRE SAFARI LODGE"
        },
        "Day 3": {
          "location": "LAKE MANYARA NATIONAL PARK",
          "property": "LAKE MANYARA HOTEL"
        },
        "Day 4": {
          "location": "SERENGETI NATIONAL PARK",
          "property": "SERENGETI SOPA LODGE"
        },
        "Day 5": {
          "location": "SERENGETI NATIONAL PARK",
          "property": "SERENGETI SOPA LODGE"
        },
        "Day 6": {
          "location": "SERENGETI NATIONAL PARK",
          "property": "SERENGETI SOPA LODGE"
        },
        "Day 7": {
          "location": "NGORONGORO CONSERVATION AREA AUTHORITY",
          "property": "NGORONGORO SOPA LODGE"
        }
      },
      "property_information": {
        "THE ARUSHA HOTEL": {
          "description": "Arusha\u2019s supreme boutique hotel offering first class accommodation and service, surrounded by the history of bygone eras. The hotel boasts the finest location in the heart of Arusha, in the tranquil surroundings of its own tropical gardens.
    
    The Arusha Hotel boasts 86 elegantly appointed rooms included 4 Suites, 25 Executive Deluxe rooms and 57 Superior Rooms. Professionally managed, we ensure the needs of every guest are carried out with East African charm and warmth.
    
    ",
          "images": [
            "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/the_arusha_hotel\/dining_parachichi.jpg",
            "http:\/\/asktechtzco.tz\/spear22\/\/images\/demo\/accommodation\/the_arusha_hotel\/images-30.jpeg",
            "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/the_arusha_hotel\/room_superior1.jpg"
          ]
        },
        "TARANGIRE SAFARI LODGE": {
          "description": "Built on top of a high bluff with a breathtaking panorama, our lodge is superbly located in Tarangire National Park, providing one of the best views in Africa.
    
    Carving out the landscape below the lodge is Tarangire River, a favourite watering place, which attracts impressive numbers and variety of game. The scene unfolds before you while lounging on the outdoor patio, allowing you to appreciate Tarangire\\\\\\\\\\\\\\&#039;s diverse wildlife without ever leaving the lodge.",
          "images": [
            "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/tarangire_safari_lodge\/images-31.jpeg",
            "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/tarangire_safari_lodge\/images-32.jpeg",
            "http:\/\/asktechtz.co.tz\/spear22\/\/images\/demo\/accommodation\/tarangire_safari_lodge\/images-33.jpeg"
          ]
        }
      }
    };
    $(function() {
      table = $("<table></table>").appendTo("#daytoday");
      table.append("<tr><th>DAY</th><th> LOCATION </th><th> HOTEL </th></tr>")
      $.each(data.glance, function(index, value) {
        row = $("<tr></tr>").appendTo(table);
        $("<td></td>").appendTo(row).html(index);
    
        $.each(value, function(i, v) {
          $("<td></td>").appendTo(row).html(v);
        });
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="daytoday">
    
    </div>

    SECOND QUESTION :

    For your second question you need to loop through the image property of valve so you need to call your loop on value.images

    So change your inner for loop like this

    for (var i = 0; i < value.images.length; i++) {
    
        if (i == 0) {
            // alert(value[i]);
            // console.log(value[i]);
            cont += '<li style="display: block;"><img src="' + value.images[i] + '" alt="" style="width:1088px;height:430px;" ></li>';
    
        } else {
            cont += '<li><img src="' + value.images[i] + '" alt="" style="width:1088px;height:430px;"></li>';
    
        }
    }
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型