Last active
October 15, 2018 11:56
-
-
Save ApoloSiskos/0c8e2b7f40e5133412f833a6f61fc119 to your computer and use it in GitHub Desktop.
Generate HTML Table from JSON (Javascript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!--<script src="https://code.jquery.com/jquery-1.9.1.js"></script>--> | |
<table id="first_version"></table> | |
<table id="second_version"> | |
<tr><th>One</th><th>Two</th><th>Three</th></tr> | |
</table> | |
<!--<div id="third_version"></div>--> | |
<script> | |
var json_data = {"headers": ["One1", "Two2", "Three3"],"rows": [["facebook", 58277, 111],["instagram", 38684, 111],["youtube", 38684, 111]]}; | |
//Version 1 - Dynamic Headers | |
var platform_data = json_data.rows; | |
var table = '<thead><tr>'; | |
//Add the headers in the table | |
json_data.headers.forEach(row => { | |
table += "<th>" + row + "</th>"; | |
}); | |
table += '</tr></thead><tbody>'; | |
//Add the rows in the table | |
json_data.rows.forEach(row => { | |
table += "<tr><td>" + row[0] + "</td><td>" + row[1] + "</td><td>" + row[2] + "</td></tr>"; | |
}); | |
table += '</tbody>'; | |
document.getElementById("first_version").innerHTML = table; | |
//Version 2 - Static Headers | |
var second_version = document.getElementById("second_version"); | |
// IE7 only supports appending rows to tbody | |
var tbody = document.createElement("tbody"); | |
// for each outer array row | |
for (var i = 0; i < platform_data.length; i++) { | |
var tr = document.createElement("tr"); | |
// for each inner array cell | |
// create td then text, append | |
for (var j = 0; j < platform_data[i].length; j++) { | |
var td = document.createElement("td"); | |
var txt = document.createTextNode(platform_data[i][j]); | |
td.appendChild(txt); | |
tr.appendChild(td); | |
} | |
// append row to table | |
// IE7 requires append row to tbody, append tbody to table | |
tbody.appendChild(tr); | |
second_version.appendChild(tbody); | |
} | |
//Version 3 - jqueryVersion | |
/* | |
var table1 = '<table id="example" class="display"><thead><tr>'; | |
$.each(data.headers, function(i) { | |
table1 +="<th>" + data.headers[i] + "</th>"; | |
}); | |
table1 +="</thead><tbody>"; | |
//Add the rows in the table | |
$.each(data.rows, function(i) { | |
table1 +="<tr><td>" + data.rows[i][0] + "</td><td>"+data.rows[i][1] +"</td><td>" +data.rows[i][2] +"</td></tr>"; | |
}); | |
table1 += '</tbody></table></div></div></div>'; | |
$("#third_version").html(table1); | |
*/ | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment