我正在尝试在 HTML 表格中显示 JSON 数据。
示例 JSON 数据
[
{
"rect": [
{
"req": "108",
"dev": "000",
"pre": "201",
"tst": "2019-08-10 18:18:10"
},
{
"req": "107",
"dev": "000",
"pre": "210",
"tst": "2019-08-04 22:05:31"
},
{
"req": "106",
"dev": "000",
"pre": "299",
"tst": "2019-08-04 20:24:40"
},
{
"req": "105",
"dev": "000",
"pre": "210",
"tst": "2019-08-04 20:24:29"
},
{
"req": "104",
"dev": "000",
"pre": "290",
"tst": "2019-08-04 20:16:07"
},
],
"ntif": {
"notification": 6
}
}
]
这是我的 JavaScript,
success: function(JSONObject) {
var peopleHTML = "";
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
peopleHTML += "<tr>";
peopleHTML += "<td>" + JSONObject["rect"][key]["req"] + "</td>";
peopleHTML += "<td>" + JSONObject["rect"][key]["pre"] + "</td>";
peopleHTML += "</tr>";
}
}
$("#people tbody").html(peopleHTML);
}
输出
加载页面时,只有前 3 个对象被 pras 到 HTML 表格中,其余数据不会显示在表格中。
如何在表格中显示全部数据?
最佳答案
您可以使用 double forEach
一次来迭代外部数组,然后迭代内部数组。
let data = [{
"rect": [{
"req": "108",
"dev": "000",
"pre": "201",
"tst": "2019-08-10 18:18:10"
},
{
"req": "107",
"dev": "000",
"pre": "210",
"tst": "2019-08-04 22:05:31"
},
{
"req": "106",
"dev": "000",
"pre": "299",
"tst": "2019-08-04 20:24:40"
},
{
"req": "105",
"dev": "000",
"pre": "210",
"tst": "2019-08-04 20:24:29"
},
{
"req": "104",
"dev": "000",
"pre": "290",
"tst": "2019-08-04 20:16:07"
},
],
"ntif": {
"notification": 6
}
}]
let peopleHTML = '';
data.forEach(function(items) {
items.rect.forEach(function(elem) {
peopleHTML += `<tr>
<td>${elem.req}</td>
<td>${elem.pre}</td>
</tr>`
})
})
$("#people tbody").html(peopleHTML);
table tbody tr td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='people'>
<tbody></tbody>
</table>
关于javascript - 遍历多维 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447571/