简体   繁体   English

如何使用 javascript 在 html 表行中提取嵌套的 json 值

[英]How to extract nested json value in a html table row using javascript

I am trying to get the object number from an array in this HTML table.我正在尝试从此 HTML 表中的数组中获取 object 编号。 And I am also trying to get the key and value of the data object in this JSON array.而且我还试图在这个 JSON 数组中获取数据 object 的键和值。 I have tried with this code and do not know how to proceed in the red marked area of the code.我已尝试使用此代码,但不知道如何在代码的红色标记区域进行操作。 Can anyone help me to find what is missing?任何人都可以帮我找到缺少的东西吗?

 var myArray = [] $.ajax({ method: 'GET', url: 'url', success: function(response) { myArray = response buildTable(myArray) console.log(myArray) } }) function buildTable(data) { var table = document.getElementById('myTable') for (var i = 0; i < data.length; i++) { var row = `<tr> <td>${data[i].}</td> // Row number <td>${data[i].date_time.substring(0, 10)}</td> <td>${data[i].date_time.substring(11, 19)}</td> <td>${data[i].data.}</td> // Measurement type, the key of data object <td>${data[i].data.}</td> // Measurement type, the value of the data object </tr>` table.innerHTML += row } }
 th { color: #fff; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <table class="table table-striped"> <tr class="bg-info"> <th>Row Number</th> <th>Date</th> <th>Time</th> <th>Measurement Type</th> <th>Value</th> </tr> <tbody id="myTable"> </tbody> </table>

The browser image is here 浏览器图片在这里

You need to extract key before building table:您需要在建表之前提取密钥:

<script>
  $.ajax({
    method:'GET',
    url:'http://webapi19sa-1.course.tamk.cloud/v1/weather',
    success:function(response){
      buildTable(response)
      console.log(response)
    }
  })

  function buildTable(data){
    const table = document.getElementById('myTable')

    for (let i = 0; i < data.length; i++) {
      const measurements = Object.keys(data[i].data);
      const value = measurements.length ? data[i].data[measurements[0]] : '';
      const name = measurements.length ? measurements[0] : '';

      const row = `
        <tr>
          <td>${i}</td>
          <td>${data[i].date_time.substring(0, 10)}</td>
          <td>${data[i].date_time.substring(11, 19)}</td>
          <td>${name}</td> 
          <td>${value}</td>
        </tr>`
      table.innerHTML += row
    }
  }
</script>

This solve your problem:这解决了你的问题:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> th{ color:#fff; } </style> <table class="table table-striped"> <tr class="bg-info"> <th>Row Number</th> <th>Date</th> <th>Time</th> <th>Measurement Type</th> <th>Value</th> </tr> <tbody id="myTable"> </tbody> </table> <script> var myArray = [] $.ajax({ method:'GET', url:'http://webapi19sa-1.course.tamk.cloud/v1/weather', success:function(response){ myArray = response buildTable(myArray) console.log(myArray) } }) function buildTable(data){ var table = document.getElementById('myTable') for (var i = 0; i < data.length; i++){ var row = `<tr> <td>${data[i].id}</td> <td>${data[i].date_time.substring(0, 10)}</td> <td>${data[i].date_time.substring(11, 19)}</td> <td>${Object.keys(data[i].data)[0]}</td> <td>${data[i].data[Object.keys(data[i].data)[0]]}</td> </tr>` table.innerHTML += row } } </script>

OP did not make use of the power of jQuery in any way. OP 没有以任何方式利用 jQuery 的力量。 So, I took the liberty of removing jQuery here altogether.所以,我冒昧地在这里完全删除了 jQuery 。 As .innerHTML+= is an "expensive" operation (it requires the DOM to be rebuilt every time) I replaced it by a faster innerHTML= assignment "outside the loop":由于.innerHTML+=是一个“昂贵”的操作(它需要每次都重建 DOM),我用更快的innerHTML=分配“循环外”替换它:

 fetch('http://webapi19sa-1.course.tamk.cloud/v1/weather').then(r=>r.json()).then(data=>document.getElementById('myTable').innerHTML=data.map(d=>`<tr> <td>${d.id}</td> <td>${d.date_time.substring(0,10)}</td> <td>${d.date_time.substring(11, 19)}</td> <td>${Object.entries(d.data||{"":""})[0].join('</td><td>')}</td></tr>` ).join('') );
 th{color:#fff;}
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <table class="table table-striped"> <tr class="bg-info"> <th>Row Number</th> <th>Date</th> <th>Time</th> <th>Measurement Type</th> <th>Value</th> </tr> <tbody id="myTable"> </tbody> </table>

With

Object.entries(d.data||{"":""})[0].join('</td><td>')

I get the first ( [0] ) key and value of an object ( .d.data ).我得到了 object ( .d.data ) 的第一个 ( [0] ) 键和值。 This expression will not break id d.data should be empty or even be non-existent.此表达式不会破坏 id d.data应该为空甚至不存在。

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

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