Skip to content

Instantly share code, notes, and snippets.

@Danny-Engelman
Last active February 14, 2019 10:44
Show Gist options
  • Save Danny-Engelman/f094e15d87797fc2205a0808db8bbeb5 to your computer and use it in GitHub Desktop.
Save Danny-Engelman/f094e15d87797fc2205a0808db8bbeb5 to your computer and use it in GitHub Desktop.
Read JSON endpoint, create TABLE HTML
//ES5 version
fetch(uri)
.then(response => response.json())
.then(json => {
// Create HTML TABLE, for a challenge refactor this to one .reduceRight call
let headers = [], maxid = 0;// maximum Primary Key value read in this DB response
// process rows first because the headers info is needed in the THEAD
let TBODY = json.map(function (row) {
headers = Object.keys(row);
let TRdata = '';// stuff all data values as data-attributes on the TR tag
let TR = headers.map(function (columnName) {
insertRow()
let value = row[columnName];
if (columnName.indexOf('_') === 0) {// its a database primary _key
if (value > maxid) maxid = value;
}
let data = ' data-' + columnName + '="' + value + '"';
TRdata += data;
return '<TD data-column="' + columnName + '" ' + data + '>' + value + '</TD>';
}).join('');
return '<TR' + TRdata + '>' + TR + '</TR>';
}).join('');
this.innerHTML = '<TABLE data-query="' + uri + '" data-maxid=' + maxid + '><THEAD><TR>'
+ headers.map(function (columnName) {
return '<TH data-column="' + columnName + '">' + columnName + '</TH>';
}).join('') + '</TR></THEAD>' + TBODY + '</TABLE>';
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment