am trying to display JSON data in an HTML table.
Sample JSON 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
}
}
]
and this is my 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);
}
Output
When loading the page, only the first 3 objects are prased into the HTML table, rest of the data are not shown in the table.
How can I display the whole data in the table?
You can use double forEach
once to iterate the outer array then inner array.
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>
You can also iterate the rect
array directly.
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 = ''; [].forEach.call(data[0].rect, 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.