Skip to content

Instantly share code, notes, and snippets.

@thegeorgeous
Created September 23, 2020 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thegeorgeous/d33483a8e7db96ac36622fe6dfdbe622 to your computer and use it in GitHub Desktop.
Save thegeorgeous/d33483a8e7db96ac36622fe6dfdbe622 to your computer and use it in GitHub Desktop.
Generating an HTML table from JSON data
// From: https://www.valentinog.com/blog/html-table/
let mountains = [
{ name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
{ name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
{ name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
{ name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
{ name: "Monte Amiata", height: 1738, place: "Siena" }
];
function generateTableHead(table, data) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key of data) {
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
}
function generateTable(table, data) {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
}
let table = document.querySelector("table");
let data = Object.keys(mountains[0]);
generateTableHead(table, data);
generateTable(table, mountains);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment