Last active
February 14, 2019 10:44
-
-
Save Danny-Engelman/f094e15d87797fc2205a0808db8bbeb5 to your computer and use it in GitHub Desktop.
Read JSON endpoint, create TABLE HTML
This file contains hidden or 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
//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