Create HTML Table using JSON data
Create HTML table from JSON data using JavaScript and JQuery
by ankit12G
HTML
<table id="lake">
<thead>
<tr>
<th>UserName</th>
<th>FirstName</th>
<th>LastName</th>
<th>MiddleName</th><th>Gender</th>
<th>Age</th>
<th>Emails</th>
<th>FavoriteFeature</th>
<th>Features</th>
</tr>
</thead>
<tbody></tbody>
</table>
CSS
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
JavaScript
var lakeData = [
{
"UserName": "russellwhyte",
"FirstName": "Russell",
"LastName": "Whyte",
"MiddleName": "dont",
"Gender": "Male",
"Age": 20,
"Emails": [
"Russell@example.com",
"Russell@contoso.com"
],
"FavoriteFeature": "Feature1",
"Features": [
"Feature1",
"Feature2"
],
"HomeAddress": null
},
{
"UserName": "scottketchum",
"FirstName": "Scott",
"LastName": "Ketchum",
"MiddleName": "dont",
"Gender": "Male",
"Age": 30,
"Emails": [
"Scott@example.com"
],
"FavoriteFeature": "Feature1",
"Features": [],
"HomeAddress": null
},
{
"UserName": "scottketchum",
"FirstName": "Scott",
"LastName": "Ketchum",
"MiddleName": "dont",
"Gender": "Male",
"Age": 30,
"Emails": [
"Scott@example.com"
],
"FavoriteFeature": "Feature1",
"Features": [],
"HomeAddress": null
}];
function addDataToTbody(nl, data) { // nl -> NodeList, data -> array with objects
data.forEach((d, i) => {
var tr = nl.insertRow(i);
Object.keys(d).forEach((k, j) => { // Keys from object represent th.innerHTML
var cell = tr.insertCell(j);
cell.innerHTML = d[k]; // Assign object values to cells
});
nl.appendChild(tr);
})
}
var lakeTbody = document.querySelector("#lake tbody");
addDataToTbody(lakeTbody, lakeData);