首页 > 解决方案 > 如何分离 json 数据的键并在表头中使用它 [javascript 或 PHP]

问题描述

我有这张表,我正在做硬编码的表头,但我希望它按照 JSON 数据模式是动态的

例如,我的 JSON 数据如下

[
  {
    "adapterid": 44835,
    "rowid": 1573784208932,
    "battery": 3610,
    "createddate": "15-11-2019",
    "gid": "01:f0:50:11:a1:35:87",
    "id": 2277491836402479600,
    "projectid": 32107,
    "rssi": -90,
    "temp": 25.75
  },
  {
    "adapterid": 44835,
    "rowid": 1573784212032,
    "battery": 3660,
    "createddate": "15-11-2019",
    "gid": "01:f0:50:11:a1:35:87",
    "id": 2277491836402479600,
    "projectid": 32107,
    "rssi": -89,
    "temp": 25.75
  },
  {
    "adapterid": 44835,
    "rowid": 1573784215034,
    "battery": 3610,
    "createddate": "15-11-2019",
    "gid": "01:f0:50:11:a1:35:87",
    "id": 2277491836402479600,
    "projectid": 32107,
    "rssi": -96,
    "temp": 25.75
  }
]

我想使用这个 JSON 数据生成表头

<thead>
    <th>adapterid</th>
    <th>rowid</th>
    <th>battery</th>
    <th>createddate</th>
    <th>gid</th>
    <th>id</th>
    <th>projectid</th>
    <th>rssi</th>
    <th>temp</th>
</thead>

标签: javascriptphpjson

解决方案


您可以使用Object.keys()从对象中获取所有键,然后遍历它们以形成标题。

演示:

var data = [
  {
    "adapterid": 44835,
    "rowid": 1573784208932,
    "battery": 3610,
    "createddate": "15-11-2019",
    "gid": "01:f0:50:11:a1:35:87",
    "id": 2277491836402479600,
    "projectid": 32107,
    "rssi": -90,
    "temp": 25.75
  },
  {
    "adapterid": 44835,
    "rowid": 1573784212032,
    "battery": 3660,
    "createddate": "15-11-2019",
    "gid": "01:f0:50:11:a1:35:87",
    "id": 2277491836402479600,
    "projectid": 32107,
    "rssi": -89,
    "temp": 25.75
  },
  {
    "adapterid": 44835,
    "rowid": 1573784215034,
    "battery": 3610,
    "createddate": "15-11-2019",
    "gid": "01:f0:50:11:a1:35:87",
    "id": 2277491836402479600,
    "projectid": 32107,
    "rssi": -96,
    "temp": 25.75
  }
]
var header = Object.keys(data[0]);
var thead = document.querySelector('table thead tr');
header.forEach(function(th){
  thead.insertAdjacentHTML('beforeend', `<th>${th}</th>`)
})
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
<table>
    <thead>
      <tr></tr>
    </thead>
</table>


推荐阅读