我有这个表,我正在做硬编码的表头,但我希望它按照 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句