javascript - 如何分离 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>
解决方案
您可以使用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>
推荐阅读
- python - 使用 Opencv python 从图像中裁剪矩形
- javascript - 通过读取 jscript 中的数组映射数据在我的 html 页面上显示警报
- yammer - Yammer API。对 AllCompany 使用 /messages/in_group/[:group_id].json
- c++ - 我必须更改我的号码最后一位和第一位,但不使用仅具有整数或循环的函数。例如从 12345 到 52341
- artificial-intelligence - Qlearning Epsilon-greedy 探索:Epsilon 衰减 X 已修复
- javascript - 每次单击按钮时我都想执行一个函数使用 JQuery
- javascript - 仅通过三角形边的长度是否足以在 WebGL 中绘制三角形?
- uml - 小型 JEE 项目的类图
- java - CardView onClick 点击测试?
- javascript - 添加第二个 addEventListener() 会破坏第一个