Skip to content

Instantly share code, notes, and snippets.

@gabrieldewes
Last active March 23, 2017 18:45
Show Gist options
  • Save gabrieldewes/97616e3684b77d23e82af440c60cbc64 to your computer and use it in GitHub Desktop.
Save gabrieldewes/97616e3684b77d23e82af440c60cbc64 to your computer and use it in GitHub Desktop.
Simple snippet to generate HTML table for JSON or Array data.
if ("undefined"===typeof jQuery) throw new Error("This function requires jQuery.");
function table(element, data) {
var g, a, b, r, i, e, l,
s = Date.now();
g = $("<table class='table table-responsive table-hover'/>").appendTo(element);
a = $("<thead />").appendTo(g);
/* Generates the table thead */
r = data[0]; // Some element of any position, use the element with more atributtes
for (i in r) {
if (r.hasOwnProperty(i)) {
e = $("<th />").appendTo(a);
l = $("<span />").appendTo(e).text(i);
}
}
/* Generates the table tbody */
a = $("<tbody />").appendTo(g);
for (i in data) {
r = data[i];
b = $("<tr />").appendTo(a);
for (k in r) {
if (r.hasOwnProperty(k)) {
e = $("<td />").appendTo(b);
l = $('<span />').appendTo(e).text(r[k]);
}
}
}
console.log("Table generated successfully", d.length, "items in", (Date.now() - s), "ms");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment