Issue
Trying to populate a table with JSON data. I'm new to JSON.
console.log(JSON.stringify(users)) =
[{
"fullname":"Bob Wirth",
"email":"Bob @mydomain.com",
"status":"A",
"lockcnt":"0",
"lastlogin":"2023-10-24 23:50:08.304896"
},{
"fullname":"Jane",
"email":"Jane@mydomain.com",
"status":"A",
"lockcnt":"0",
"lastlogin":"2023-11-03 11:31:57.18215"
}]
How do I build an each to iterate through each object and then each property so I can generate the tr tag on the object and td on the property.
Solution
If we don't make any assumptions, like you want the table to display the Keys as the Headers, then you will want to perform a loop with a nested loop. The first loop will create the Rows, from each element of the Array. The second loop will populate the Cells from the Object.
A basic example:
$(function() {
var users = [{
"fullname": "Bob Wirth",
"email": "Bob @mydomain.com",
"status": "A",
"lockcnt": "0",
"lastlogin": "2023-10-24 23:50:08.304896"
}, {
"fullname": "Jane",
"email": "Jane@mydomain.com",
"status": "A",
"lockcnt": "0",
"lastlogin": "2023-11-03 11:31:57.18215"
}];
function makeTable(bodyData, target) {
var $t = $("<table>");
$.each(bodyData, function(key, row) {
$("<tr>").appendTo($t);
$.each(row, function(i, cell) {
$("<td>").html(cell).appendTo($("tr:last", $t));
});
});
if (target != undefined) {
$(target).html($t);
}
return $t;
}
makeTable(users, "#results");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results"></div>
From this, you could perform a lot of additional steps, for example, you could collect the Keys from one of the Objects and build headers for the Table.
There re also a lot of frameworks that can be used, like Datatables, that will do this all for you.
Answered By - Twisty
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.