Last active
January 27, 2016 00:49
-
-
Save maxali/bb2f539cf2a79cfa8aea to your computer and use it in GitHub Desktop.
JSON to Table
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
<!DOCTYPE html> | |
<html> | |
<head>JSON to Table</head> | |
<body> | |
<button type="button" value="Process" onclick="json2table('mytable')"> | |
<table id='mytable'></table> | |
</body> | |
</html> |
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
function json2table(tbl){ | |
data = [{id:1,name:'ASAD'},{id:2, name:'DAN'}]; | |
//tbl: table id | |
var table = document.getElementById(tbl); | |
console.log(table); | |
var cols=[]; | |
var thr = document.createElement('tr'); | |
var tb = document.createElement('tbody'); | |
tb.innerHTML = ""; | |
data.forEach(function(item, i){ | |
for(var prop in item) { | |
if(cols.indexOf(prop) == -1) { | |
cols.push(prop); | |
var th = document.createElement('th'); | |
th.innerHTML = prop; | |
thr.appendChild(th); | |
} | |
} | |
}) | |
// table head | |
var th = document.createElement('thead'); | |
th.style.fontSize = "large"; | |
th.innerHTML = ""; | |
th.appendChild(thr); | |
//build body rows | |
data.forEach(function(item, i){ | |
var tr = document.createElement('tr'); | |
for(var col in cols) { | |
var td = document.createElement('td'); | |
td.innerHTML = item[cols[col]] || ""; | |
tr.appendChild(td); | |
} | |
tb.appendChild(tr); | |
}) | |
table.innerHTML = ""; | |
table.appendChild(th); | |
table.appendChild(tb); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment