gpt4 book ai didi

javascript - 在 javascript 中从 JSON 生成 HTML 表

转载 作者:行者123 更新时间:2023-12-03 07:08:13 24 4
gpt4 key购买 nike

我想从这种类型的 JSON 生成 HTML 表:

{  
"fields":{
"Product.Name":[
"ql23xx-firmware",
"setup",
"ql2500-firmware"
],
"Product.Version":[
"3.03.27-3.1.el6-noarch",
"2.8.14-13.el6-noarch",
"5.06.02-1.el6-noarch"
],
"Id":[
"tdcapa11s"
],
"CMDB.EntityInCharge":[
"SUP.CA_SYS"
]
}
}

我可以轻松地制作一个表格,如下所示:

<table>
<thead>
<tr>
<th>Id</th>
<th>CMDB.EntityInCharge</th>
<th>Product.Name</th>
<th>Product.Version</th>
</tr>
</thead>
<tbody>
<tr>
<td>tdcapa11s</td>
<td>SUP.CA_SYS</td>
<td>ql23xx-firmware, setup, ql2500-firmware</td>
<td>3.03.27-3.1.el6-noarch, 2.8.14-13.el6-noarch, 5.06.02-1.el6-noarch</td>
</tr>
</tbody>
</table>

但我想要类似的东西:

<table>
<thead>
<tr>
<th>Id</th>
<th>CMDB.EntityInCharge</th>
<th>Product.Name</th>
<th>Product.Version</th>
</tr>
</thead>
<tbody>
<tr>
<td>tdcapa11s</td>
<td>SUP.CA_SYS</td>
<td>ql23xx-firmware</td>
<td>3.03.27-3.1.el6-noarch</td>
</tr>
<tr>
<td>tdcapa11s</td>
<td>SUP.CA_SYS</td>
<td>setup</td>
<td>2.8.14-13.el6-noarch</td>
</tr>
<tr>
<td>tdcapa11s</td>
<td>SUP.CA_SYS</td>
<td>ql2500-firmware</td>
<td>5.06.02-1.el6-noarch</td>
</tr>
</tbody>
</table>

如何用 Javascript 生成它?

我离这个并不远,但对于这样一个简单的事情来说,我的 javascript 代码实际上很长

最佳答案

这是一种方法:

body_row.append( td.clone().html( (field == 'Id' || field == 'CMDB.EntityInCharge') ? data.fields[field][0] : data.fields[field][i] ) );

如下面的演示所示:

var data = {  
"fields":{
"Id":[
"tdcapa11s"
],
"CMDB.EntityInCharge":[
"SUP.CA_SYS"
],
"Product.Name":[
"ql23xx-firmware",
"setup",
"ql2500-firmware"
],
"Product.Version":[
"3.03.27-3.1.el6-noarch",
"2.8.14-13.el6-noarch",
"5.06.02-1.el6-noarch"
]
}
}
var table = $('<table/>'),
thead = $('<thead/>'),
tbody = $('<tbody/>'),
tr = $('<tr/>'),
th = $('<th/>'),
td = $('<td/>');
//header row
var hrow = tr.clone();
for(field in data.fields) {
hrow.append( th.clone().html( field ) );
}
//append row to thead and table
table.html( thead.html( hrow ) );
//body rows
for( var i = 0; i < data.fields["Product.Name"].length; i++ ) {
var brow = tr.clone();
for(field in data.fields) {
brow.append( td.clone().html( (field == 'Id' || field == 'CMDB.EntityInCharge') ? data.fields[field][0] : data.fields[field][i] ) );
}
//append row to tbody
tbody.append( brow );
}
//append tbody to table
table.append( tbody );
//append table to page
$('#table').html( table );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table"></div>

关于javascript - 在 javascript 中从 JSON 生成 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36720066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com