Generate table from Object data - javascript

I have an object like the one below:
var obj = {
a : {
x : 1,
y : 2,
z : 3
},
b : {
x : 1,
y : 2,
z : 3
}
}
With it, I will like to generate the following table. Format is showed bellow
http://jsfiddle.net/gD87t/
I am trying to get the elements from object and and trying to append but getting confused with the rowSpan value
var tr = document.createElement('tr');
for(var i in obj){
var td = document.createElement('td');
td.rowSpan = ? // Here I am getting confused.
}
Can a template engine solve my problem?
What is the best way to do this?

Here's one way of doing it with a recursive function in pure js:
function addObjectToTable(table, obj, tr) {
var rows = 0;
for (key in obj) {
if (tr == null) {
tr = document.createElement('tr');
table.appendChild(tr);
}
var td = document.createElement('td');
td.textContent = key;
tr.appendChild(td);
var value = obj[key];
if (typeof value != 'object') {
var td = document.createElement('td');
td.textContent = value;
tr.appendChild(td);
rows += 1;
}
else {
var subrows = addObjectToTable(table, value, tr);
td.setAttribute('rowspan',subrows);
rows += subrows;
}
tr = null;
}
return rows;
}
Which would be called like this:
var table = document.createElement('table');
addObjectToTable(table,obj);
document.body.appendChild(table);
Note that when first called, the tr parameter is null, since we always have to create a new row at the top level. When the function is called recursively though, the tr parameter is passed in from the upper level since lower levels will intially be adding to the the row of their parent object.
The function returns the number of rows added, so when it is called recusively the caller will know what to set the rowspan value to.
Fiddle link

I couldn't find an answer which handled circulars, and I also decided to do this without any unnecessary DOM writes. Also, I didn't follow the exact mark-up the OP requested because I felt nesting tables was more convenient for a recursive operation such as this- and serves close to the same visual purpose.
So, here's the function I've created:
function dataToTable (data) {
var storage = [];
return (function buildTable (data) {
var table = '<table><tbody>';
var name, value;
// Add the object/array to storage for cirular detection.
storage.push(data);
for (name in data) {
value = data[name];
table += '<tr><td>' + name + '</td><td>';
// If the value is an object we've put in storage (circular)
if (storage.indexOf(value) !== -1) {
table += '<em>Circular</em>';
} else if (typeof value === 'object') {
table += buildTable(value);
} else {
table += value;
}
table += '</td></tr>';
}
return table + '</tbody></table>';
}(data));
}
Here is the object I used to test:
var obj = {
a : {
x : 1,
y : 2,
z : 3
},
b : {
x : 1,
y : 2,
z : {
test1: 0,
test2: {
test3: 1,
test4: ['a','b','c']
}
}
}
};
obj.c = obj;
obj.b.z.test2.test4.push(obj.a);
The function will turn this object into an HTML table. What you do with the table is up to you. On my fiddle, I used the DOM to add the table to a DIV (document.getElementById).
http://jsfiddle.net/5RhXF/1/
I hope you'll find my implementation clear.
UPDATE::
I decided to test this on the jQuery library, and it worked! Except, the functions were printing as their toString value with no good format for text.. Which makes sense, but not very helpful. So, I'm thinking this is a nice and easy way to look through APIs for frameworks/libraries and what-not. Therefore, I added prettify for syntax-highlighting of functions, and also added a type-check for functions in the table generator, and a quick class to get rid of borders around the prettify box (as there's already a border on the table cell). If anyone is interested in the version designed for source-reading/debugging, here's the fiddle:
http://jsfiddle.net/5RhXF/7/

UPDATED: if you don't need empty cells solution could be (check fiddle http://jsfiddle.net/gD87t/11/)
Example object :
var obj = {
a : {
x : 1,
y : 2,
z : {
c : 4,
d : 5
}
},
b : {
x : 1,
y : 2,
z : 3
}
}
And routine to build table:
function merge(rows , inner) {
inner.reduce(function (i, p) {
rows.push(i)
})
}
function getRows(o) {
var rows = []
if (typeof o == 'object') {
for (var k in o) {
var innerRows = getRows(o[k])
, firstCell = $('<td />')
.text(k)
.attr('rowspan',innerRows.length)
innerRows[0].prepend(firstCell)
rows = rows.concat(innerRows)
}
} else {
var tr = $('<tr />')
, td = $('<td />').text(o)
tr.append(td)
rows.push(tr)
}
return rows
}
function buildTable(o, $t) {
var rows = getRows(o)
$t.append(rows)
}
buildTable(obj, $('#table2'))

The value for the rowspan is the number of properties in the inner object. You can use the Object.keys function to get a list of the keys on the object, then use its length property to determine how many properties there are:
for(var i in obj){
var td = document.createElement('td');
td.rowSpan = Object.keys(obj[i]).length;
}

var table = document.createElement('table');
var i, j;
var row, cell;
for(i in obj) {
if(obj.hasOwnProperty(i)) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.rowSpan = Object.keys(obj[i]).length;
cell.innerText = i;
row.appendChild(cell);
for(j in obj[i]) {
if(obj[i].hasOwnProperty(j)) {
cell = document.createElement('td');
cell.innerText = j;
row.appendChild(cell);
cell = document.createElement('td');
cell.innerText = obj[i][j];
row.appendChild(cell);
table.appendChild(row);
row = document.createElement('tr');
}
}
}
}
document.body.appendChild(table);
Of course, it would look less verbose in jQuery. But it looked like you wanted to do it in plain DOM.
See it woking

well it was really tricky but I think it is done. By the way I still suggest table-less solution. you can check the working code here
var obj = {
a : {
x : 1,
y : 2,
z : {c:1, d:3}
},
b : {
x : 1,
y : 2,
z : 3
}
}
var table = document.createElement('table');
function createTable (o, parentCells) {
for (var key in o) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.rowSpan = 1;
cell.innerText = key;
if (typeof o[key] !== "object") {
var cellv = document.createElement('td');
cellv.innerText = o[key];
row.appendChild(cell);
row.appendChild(cellv);
table.appendChild(row);
}
else {
for (var i = 0; i < parentCells.length; i++) {
parentCells[i].rowSpan += Object.keys(o[key]).length;
}
cell.rowSpan += Object.keys(o[key]).length;
var newParentCells = new Array(parentCells);
newParentCells.push(cell);
row.appendChild(cell);
table.appendChild(row);
createTable(o[key], newParentCells);
}
}
}
createTable(obj, []);
document.body.appendChild(table);

If you wish to use document.createElement as you do in your question, the easiest way is probably like this:
function generateTable(o) {
var table, tr, td, i, j, l, keys;
table = document.createElement('table')
for(i in o){
tr = document.createElement('tr');
table.appendChild(tr);
td = document.createElement('td');
keys = Object.keys(o[i]);
td.rowSpan = keys.length;
td.textContent = i;
tr.appendChild(td);
x=0;
for(j=0;j<keys.length;j++) {
if(j) {
tr = document.createElement('tr');
table.appendChild(tr);
}
td = document.createElement('td');
td.textContent = keys[j];
tr.appendChild(td);
td = document.createElement('td');
td.textContent =o[i][keys[j]];
tr.appendChild(td);
}
}
return table;
}
CAVEAT: Object.keys isn't available in older browsers so you'll need a polyfill like this:
(taken from MOZILLA DEVELOPER NETWORK)
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
};
})();
}
Alternatively there is a much simpler polyfill that will cover most cases quite well here:
(Taken from Token Posts)
if (!Object.keys) Object.keys = function(o) {
if (o !== Object(o))
throw new TypeError('Object.keys called on a non-object');
var k=[],p;
for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
return k;
}
You can see a fiddle of it in action here: http://jsfiddle.net/uyJv2/

Related

How to add different columns to a dynamic table from database with javascript

I have a function building a dynamic table. I'm having trouble figuring out how to set each column to a different data set from the database. Right now it just shows the same value in each column.
A little background. I'm building a table with 6 columns and lots of rows (all depends how much data the database has). Right now it's only showing one column in all of the 6 columns, so they repeat.
How can I set each column to a different value for the 6 columns?
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
Here is the ajax call:
function triggerDataTable(index) {
// Make AJAX requests for model systems
$.ajax({
type: "POST",
url: "qry/getAllData.php",
async: true,
dataType: "html",
data: {ErrorOptions: control.settings.errorOptions},
success: function (result) {
//console.warn(result);
errorData = JSON.parse(result);
//loop through data
var len = errorData.length;
for(i=0; i<len; i++) {
if ('VersionKey' in errorData[i]) {
vKey = (errorData[i]['VersionKey']);
} else if ('ErrorCode' in errorData[i]) {
var errorCode = (errorData[i]['ErrorCode']);
} else if ('SourceKey' in errorData[i]) {
var sourceKey = (errorData[i]['SourceKey']);
} else { //data here
errorTableData = errorData[i];
}
}
addTable();
}
});
}
The errorData is the data from the database. As you can see I've tried to add 2 variables but when I do that it just puts both of them in the same box and repeats throughout the whole table.
It looks like you are printing the exact same data 6 times for each row. You create a td element, then add country and state names to it, but the variable you are using for the index on your data set is coming from your outer loop, so on the inner loop it never changes, and you are literally grabbing the same value every time:
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
// You set i here, presumably to get each row in your dataset
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
// Above, you are using i, not j
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
It would be easier to help if you could post some json with the data you are getting from the DB
Based on the edit on your post and looking at the success callback, I think you have small problem that can be easily fixed:
First, initialize an empty array for errorTableData
success: function (result) {
errorTableData = [];
In your if/else block:
} else { //data here
errorTableData = errorData[i];
}
Should be:
} else { //data here
errorTableData[i] = errorData[i];
}
Then in your inner loop:
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
Becomes:
var countyName = errorTableData[i]['CountyName'][j];
var stateName = errorTableData[i]['StateName'][j];
This is just a guess because I can't see the actual data.

Create table from Json pure javascript

I have a Json with multiple keys that can change, something like this:
Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}]
And I want a table with the headers (num, name, phone)
How can I do it with only JavaScript? (No JQuery)
var children = [{num: 6, name: 'me', phone: 7}, {num: 8, name: 'him', phone: 9}];
function addHeaders(table, keys) {
var row = table.insertRow();
for( var i = 0; i < keys.length; i++ ) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(keys[i]));
}
}
var table = document.createElement('table');
for( var i = 0; i < children.length; i++ ) {
var child = children[i];
if(i === 0 ) {
addHeaders(table, Object.keys(child));
}
var row = table.insertRow();
Object.keys(child).forEach(function(k) {
console.log(k);
var cell = row.insertCell();
cell.appendChild(document.createTextNode(child[k]));
})
}
document.getElementById('container').appendChild(table);
<div id="container"></div>
The below method will draw a table based on json.
First Copy the javascript and html
javascript
<script type="text/javascript">
function jsonToTable(json) {
var parsejson=JSON.parse(json);
var columns=[];
var tablethread="<thead><tr>";
for (x in parsejson[0]) {
columns.push(x);
tablethread+="<th>"+x+"</th>";
}
tablethread+="</tr></thead>";
document.getElementById("tableID").innerHTML=tablethread;
var table_rows='<tbody>';
for (var i = 0; i < parsejson.length; i++) {
var x= parsejson[i];
var json2=x;
var row="<tr>"
for (d in x) {
var sty=x[d];
if (sty!=null) {
var st=sty.toString();
var reps='<\\';
row+="<td><p>"+st.split('<').join('<')+"</p></td>";
}
else {
row+="<td><p>null</p></td>";
}
}
row+="</tr>"
table_rows+=row;
}
table_rows+='</tbody>';
document.getElementById("tableID").innerHTML+=table_rows;
}
</script>
HTML
<table id="tableID" class="table"></table>
Now Call Method
jsonToTable("YOUR_JSON");
Example
var jsonstring = '[{ "name":"John", "age":30, "car":"BMW"},'+
'{ "name":"Wick", "age":50,"car":"DODGE" }]';
jsonToTable(jsonstring);
fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(data => createTable(data)).catch(error=>console.log(error))
const createTable = (data) => {
const tableData = data;
const headerData = Object.keys(tableData[0]);
const table = document.createElement('table');
const tr = table.insertRow(-1);
for(let i=0; i<headerData.length; i++){
const th = document.createElement('th');
th.innerHTML = headerData[i];
tr.appendChild(th)
}
for(let i=0; i<tableData.length; i++){
const tr = table.insertRow(-1);
const obj = tableData[i];
for(let key in obj) {
const td = document.createElement('td');
td.innerHTML = obj[key];
tr.appendChild(td);
}
}
document.body.appendChild(table);
}
Javascript
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i=0, maxi=arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j=0, maxj=columns.length; j < maxj ; ++j) {
var td = _td_.cloneNode(false);
cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table)
{
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i=0, l=arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
columnSet.push(key);
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
document.body.appendChild(buildHtmlTable([
{"num" : "6", "name" : "me", "phone" : "7"},
{"num" : "8", "name" : "him", "phone" : "9"}
]));
CSS
th, td {
border: 1px solid;
}
th {
font-weight : bold
}

Not sure I quite understand variable scope in Javascript

Sorry if this seems a bit easy. I'm still relatively new to Javascript.
I am generating a list of checkboxes. On the onClick of a checkbox, i want to make it pop up its associated text. ie. Checkbox named "one" should then display "one". In my example it only displays "two".
However the click() callback method only ever calls the text of the last added checkbox. Does the 'v' variable in here not get assigned per checkbox? It seems like the'v' is behaving like a global variable.
this.view = document.createElement("div");
var tbody = document.createElement("tbody");
var popupValues = {"A", "B"};
for (var i=0;i<this.popupValues.length;i++) {
var v = popupValues[i];
var tr = document.createElement('tr');
var tdCheck = document.createElement('td');
var ChkBx = document.createElement('input')
ChkBx.type = 'checkbox';
tdCheck.appendChild(ChkBx);
var self = this;
$(ChkBx).live('change', function(){
if($(this).is(':checked')){
alert('checked' + v);
} else {
alert('un-checked' + v);
}
});
var td = document.createElement("td");
td.appendChild(document.createTextNode('' + v));
tr.appendChild(tdCheck);
tr.appendChild(td);
tbody.appendChild(tr);
}
table.appendChild(tbody);
document.appendChild(table)
Here is jsfiddle :
http://jsfiddle.net/n5GZW/2/
Anyone know what I am doing wrong?
UPDATE: updated JSFiddle
"Does the 'v' variable in here not get assigned per checkbox?"
Well, it's assigned, but not declared for each checkbox.
In Javascript variables only have function scope. Even if you try to create a new variable in each iteration of the loop, it's only a single variable declared at the function level, shared by all iterations. The declaration is hoisted to the function level, only the assignment happens inside the loop.
You can use an immediatey executed function expression to create another scope inside the loop, where you can create a new variable for each iteration:
for (var i=0;i<this.popupValues.length;i++) {
(function(v){
// code of the loop goes in here
// v is a new variable for each iteration
}(popupValues[i]));
}
you can do
var table = document.createElement("table");
var tbody = document.createElement("tbody");
var popupValues = [
"one", "two"
];
for (var i = 0; i < popupValues.length; i++) {
var v = popupValues[i];
var tr = document.createElement('tr');
var tdCheck = document.createElement('td');
var ChkBx = document.createElement('input');
ChkBx.type = 'checkbox';
ChkBx.value=v;
tdCheck.appendChild(ChkBx);
var td = document.createElement("td");
td.appendChild(document.createTextNode('' + v));
tr.appendChild(tdCheck);
tr.appendChild(td);
tbody.appendChild(tr);
var self = this;
$(ChkBx).click('change', function () {
if ($(this).is(':checked')) {
alert('check ' + $(this).val());
} else {
alert('un-checked');
}
});
}
table.appendChild(tbody);
document.body.appendChild(table)
http://jsfiddle.net/n5GZW/4/
add ChkBx.value=v; to get value like $(this).val() on click
You could've searched in SO for event binding in for loop.
Here is one solution:
Try this:
this.view = document.createElement("div");
var tbody = document.createElement("tbody");
var popupValues = {"A", "B"};
for (var i=0;i<this.popupValues.length;i++) {
var v = popupValues[i];
var tr = document.createElement('tr');
var tdCheck = document.createElement('td');
var ChkBx = document.createElement('input')
ChkBx.type = 'checkbox';
tdCheck.appendChild(ChkBx);
var self = this;
(function(val) {
$(ChkBx).on('change', function(){
if($(this).is(':checked')){
alert('checked' + val);
} else {
alert('un-checked' + val);
}
});
})(v);
var td = document.createElement("td");
td.appendChild(document.createTextNode('' + v));
tr.appendChild(tdCheck);
tr.appendChild(td);
tbody.appendChild(tr);
}
table.appendChild(tbody);
document.appendChild(table);

Javascript dynamic rows column

I am new to javascript. I have a table of content which I want to rearrange its row and column based on user's window size using window.onresize.
window.onresize = function () {
var w = window.innerWidth;
var nocolumn = Math.floor(w / 252);
if (nocolumn == 0) {
nocolumn = 1;
}
var table = document.getElementById("MainContent_DataList1");
var tbody = table.getElementsByTagName("tbody")[0];
var link = tbody.getElementsByTagName("a");
var norow = Math.ceil(link.length / nocolumn);
tbody.innerHTML = "";
console.log(norow + " " + link.length + " " + nocolumn);
for (var i = 0; i < norow; i++) {
var row = document.createElement("tr");
tbody.appendChild(row);
for (var j = 0; j < nocolumn; j++) {
var cell = document.createElement("td");
row.appendChild(cell);
if ((i * nocolumn + j) < link.length) {
cell.appendChild(link[i * nocolumn + j]);
}
}
}
};
I dont understand why the variable "link" array becomes empty after I use innerHTML = ""; but I stored it before its cleared. Is it somewhere I did wrongly or there are other ways to do this?
When you delete the innerHTML you delete the DOM objects thus every reference to them will point to null.
A work around it will be to clone these objects:
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
window.onresize = function () {
var w = window.innerWidth;
var nocolumn = Math.floor(w / 252);
if (nocolumn == 0) {
nocolumn = 1;
}
var table = document.getElementById("MainContent_DataList1");
var tbody = table.getElementsByTagName("tbody")[0];
var tmp = tbody.getElementsByTagName("a");
var link = clone(tmp);
var norow = Math.ceil(link.length / nocolumn);
tbody.innerHTML = "";
...
}
Credit for the clone() method: https://stackoverflow.com/a/728694/1057429
As other answers have suggested, getElementsByTagName returns a live NodeList. Therefore, when you delete all the elements from the body, the NodeList is updated to contain no nodes.
As an alternative, you can use querySelectorAll, which returns a static NodeList, or use getElementsByTagName and assign references to an array before clearing the nodes from the body, e.g.
function getNodes() {
var tbody = document.body || document.getElementsByTagName('body')[0];
var nodes, link;
if (tbody.querySelectorAll) {
link = tbody.querySelectorAll('*');
} else {
nodes = tbody.getElementsByTagName("*");
link = [];
for (var i=0, iLen=nodes.length; i<iLen; i++) {
link[i] = nodes[i];
}
}
return link;
}

Convert JSON array to an HTML table in jQuery

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?
Using jQuery will make this simpler.
The following code will take an array of arrays and store convert them into rows and cells.
$.getJSON(url , function(data) {
var tbl_body = "";
var odd_even = false;
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
});
tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
odd_even = !odd_even;
});
$("#target_table_id tbody").html(tbl_body);
});
You could add a check for the keys you want to exclude by adding something like
var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
at the start of the getJSON callback function and adding:
if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}
around the tbl_row += line.
Edit: Was assigning a null variable previously
Edit: Version based on Timmmm's injection-free contribution.
$.getJSON(url , function(data) {
var tbl_body = document.createElement("tbody");
var odd_even = false;
$.each(data, function() {
var tbl_row = tbl_body.insertRow();
tbl_row.className = odd_even ? "odd" : "even";
$.each(this, function(k , v) {
var cell = tbl_row.insertCell();
cell.appendChild(document.createTextNode(v.toString()));
});
odd_even = !odd_even;
});
$("#target_table_id").append(tbl_body); //DOM table doesn't have .appendChild
});
I'm not sure if is this that you want but there is jqGrid. It can receive JSON and make a grid.
Make a HTML Table from a JSON array of Objects by extending $ as shown below
$.makeTable = function (mydata) {
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
tblHeader += "</tr>";
$(tblHeader).appendTo(table);
$.each(mydata, function (index, value) {
var TableRow = "<tr>";
$.each(value, function (key, val) {
TableRow += "<td>" + val + "</td>";
});
TableRow += "</tr>";
$(table).append(TableRow);
});
return ($(table));
};
and use as follows:
var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");
where TableCont is some div
Pure HTML way, not vulnerable like the others AFAIK:
// Function to create a table as a child of el.
// data must be an array of arrays (outer array is rows).
function tableCreate(el, data)
{
var tbl = document.createElement("table");
tbl.style.width = "70%";
for (var i = 0; i < data.length; ++i)
{
var tr = tbl.insertRow();
for(var j = 0; j < data[i].length; ++j)
{
var td = tr.insertCell();
td.appendChild(document.createTextNode(data[i][j].toString()));
}
}
el.appendChild(tbl);
}
Example usage:
$.post("/whatever", { somedata: "test" }, null, "json")
.done(function(data) {
rows = [];
for (var i = 0; i < data.Results.length; ++i)
{
cells = [];
cells.push(data.Results[i].A);
cells.push(data.Results[i].B);
rows.push(cells);
}
tableCreate($("#results")[0], rows);
});
Converting a 2D JavaScript array to an HTML table
To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$('body').append(arrayToTable([
["John","Slegers",34],
["Tom","Stevens",25],
["An","Davies",28],
["Miet","Hansen",42],
["Eli","Morris",18]
]));
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Loading a JSON file
If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :
$.ajax({
type: "GET",
url: "data.json",
dataType: 'json',
success: function (data) {
$('body').append(arrayToTable(data));
}
});
For very advanced JSON objects to HTML tables you can try My jQuery Solution that is based on this closed thread.
var myList=[{"name": "abc","age": 50},{"name": {"1": "piet","2": "jan","3": "klaas"},"age": "25","hobby": "watching tv"},{"name": "xyz","hobby": "programming","subtable": [{"a": "a","b": "b"},{"a": "a","b": "b"}]}];
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable() {
addTable(myList, $("#excelDataTable"));
}
function addTable(list, appendObj) {
var columns = addAllColumnHeaders(list, appendObj);
for (var i = 0; i < list.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = list[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
if (cellValue.constructor === Array)
{
$a = $('<td/>');
row$.append($a);
addTable(cellValue, $a);
} else if (cellValue.constructor === Object)
{
var array = $.map(cellValue, function (value, index) {
return [value];
});
$a = $('<td/>');
row$.append($a);
addObject(array, $a);
} else {
row$.append($('<td/>').html(cellValue));
}
}
appendObj.append(row$);
}
}
function addObject(list, appendObj) {
for (var i = 0; i < list.length; i++) {
var row$ = $('<tr/>');
var cellValue = list[i];
if (cellValue == null) {
cellValue = "";
}
if (cellValue.constructor === Array)
{
$a = $('<td/>');
row$.append($a);
addTable(cellValue, $a);
} else if (cellValue.constructor === Object)
{
var array = $.map(cellValue, function (value, index) {
return [value];
});
$a = $('<td/>');
row$.append($a);
addObject(array, $a);
} else {
row$.append($('<td/>').html(cellValue));
}
appendObj.append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(list, appendObj)
{
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < list.length; i++) {
var rowHash = list[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
appendObj.append(headerTr$);
return columnSet;
}
One simple way of doing this is:
var data = [{
"Total": 34,
"Version": "1.0.4",
"Office": "New York"
}, {
"Total": 67,
"Version": "1.1.0",
"Office": "Paris"
}];
drawTable(data);
function drawTable(data) {
// Get Table headers and print
var head = $("<tr />")
$("#DataTable").append(head);
for (var j = 0; j < Object.keys(data[0]).length; j++) {
head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));
}
// Print the content of rows in DataTable
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#DataTable").append(row);
row.append($("<td>" + rowData["Total"] + "</td>"));
row.append($("<td>" + rowData["Version"] + "</td>"));
row.append($("<td>" + rowData["Office"] + "</td>"));
}
table {
border: 1px solid #666;
width: 100%;
text-align: center;
}
th {
background: #f8f8f8;
font-weight: bold;
padding: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="DataTable"></table>
You could use a jQuery plugin that accepts JSON data to fill a table.
jsonTable
I found a duplicate over here: Convert json data to a html table
Well, there are many plugins exists, including commercial one (Make this as commercial project?! Kinda overdone... but you can checkout over here: https://github.com/alfajango/jquery-dynatable)
This one has more fork: https://github.com/afshinm/Json-to-HTML-Table
//Example data, Object
var objectArray = [{
"Total": "34",
"Version": "1.0.4",
"Office": "New York"
}, {
"Total": "67",
"Version": "1.1.0",
"Office": "Paris"
}];
//Example data, Array
var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"];
//Example data, nested Object. This data will create nested table also.
var nestedTable = [{
key1: "val1",
key2: "val2",
key3: {
tableId: "tblIdNested1",
tableClassName: "clsNested",
linkText: "Download",
data: [{
subkey1: "subval1",
subkey2: "subval2",
subkey3: "subval3"
}]
}
}];
Apply the code
//Only first parameter is required
var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');
Or you might want to checkout this jQuery plugins as well: https://github.com/jongha/jquery-jsontotable
I think jongha's plugins is easier to use
<div id="jsontotable" class="jsontotable"></div>
var data = [[1, 2, 3], [1, 2, 3]];
$.jsontotable(data, { id: '#jsontotable', header: false });
If you accept using another jQuery dependent tool, I would recommend using Tabulator. Then you will not need to write HTML or any other DOM generating code, while maintaining great flexibility regarding the formatting and processing of the table data.
For another working example using Node, you can look at the MMM-Tabulator demo project.
with pure jquery:
window.jQuery.ajax({
type: "POST",
url: ajaxUrl,
contentType: 'application/json',
success: function (data) {
var odd_even = false;
var response = JSON.parse(data);
var head = "<thead class='thead-inverse'><tr>";
$.each(response[0], function (k, v) {
head = head + "<th scope='row'>" + k.toString() + "</th>";
})
head = head + "</thead></tr>";
$(table).append(head);//append header
var body="<tbody><tr>";
$.each(response, function () {
body=body+"<tr>";
$.each(this, function (k, v) {
body=body +"<td>"+v.toString()+"</td>";
})
body=body+"</tr>";
})
body=body +"</tbody>";
$(table).append(body);//append body
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responsetext);
}
});
You can do this pretty easily with Javascript+Jquery as below.
If you want to exclude some column, just write an if statement inside the for loops to skip those columns. Hope this helps!
//Sample JSON 2D array
var json = [{
"Total": "34",
"Version": "1.0.4",
"Office": "New York"
}, {
"Total": "67",
"Version": "1.1.0",
"Office": "Paris"
}];
// Get Table headers and print
for (var k = 0; k < Object.keys(json[0]).length; k++) {
$('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');
}
// Get table body and print
for (var i = 0; i < Object.keys(json).length; i++) {
$('#table_content').append('<tr>');
for (var j = 0; j < Object.keys(json[0]).length; j++) {
$('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');
}
$('#table_content').append('</tr>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr id="table_head">
</tr>
</thead>
<tbody id="table_content">
</tbody>
</table>
Modified a bit code of #Dr.sai 's code. Hope this will be useful.
(function ($) {
/**
* data - array of record
* hidecolumns, array of fields to hide
* usage : $("selector").generateTable(json, ['field1', 'field5']);
*/
'use strict';
$.fn.generateTable = function (data, hidecolumns) {
if ($.isArray(data) === false) {
console.log('Invalid Data');
return;
}
var container = $(this),
table = $('<table>'),
tableHead = $('<thead>'),
tableBody = $('<tbody>'),
tblHeaderRow = $('<tr>');
$.each(data, function (index, value) {
var tableRow = $('<tr>').addClass(index%2 === 0 ? 'even' : 'odd');
$.each(value, function (key, val) {
if (index == 0 && $.inArray(key, hidecolumns) <= -1 ) {
var theaddata = $('<th>').text(key);
tblHeaderRow.append(theaddata);
}
if ($.inArray(key, hidecolumns) <= -1 ) {
var tbodydata = $('<td>').text(val);
tableRow.append(tbodydata);
}
});
$(tableBody).append(tableRow);
});
$(tblHeaderRow).appendTo(tableHead);
tableHead.appendTo(table);
tableBody.appendTo(table);
$(this).append(table);
return this;
};
})(jQuery);
Hoping this will be helpful to hide some columns too.
Link to file
Pivoted single-row view with headers on the left based on #Dr.sai's answer above.
Injection prevented by jQuery's .text method
$.makeTable = function (mydata) {
var table = $('<table>');
$.each(mydata, function (index, value) {
// console.log('index '+index+' value '+value);
$(table).append($('<tr>'));
$(table).append($('<th>').text(index));
$(table).append($('<td>').text(value));
});
return ($(table));
};
Make a HTML Table from a JSON array of Objects by extending $ as shown below
$.makeTable = function (mydata, cssClass) {
if (!cssClass) cssClass = "table table-bordered table-stripped table-dark"
var table = $('<table class="' + cssClass + '">');
var tblHeader = "<thead><tr>";
for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
tblHeader += "</tr></thead>";
$(tblHeader).appendTo(table);
var TableRow = "<tbody>";
$.each(mydata, function (index, value) {
TableRow += "<tr id=_ID_>".replace("_ID_", value.name);
$.each(value, function (key, val) {
TableRow += "<td>" + val + "</td>";
});
TableRow += "</tr>";
});
TableRow += "</tbody>";
$(table).append(TableRow);
return ($(table));
};
Usage as Below
var EmployeeArr = [];
for (let i = 0; i < 100; ++i) {
let emp = {};
emp.name = "Varsha_" + i;
emp.age = Math.round((Math.random() * 100 + 10)) * 3
EmployeeArr.push(emp);
}
var table = $.makeTable(EmployeeArr );
$(table).appendTo("#TableCont");
where TableCont is some div
A still shorter way
$.makeTable = function (mydata) {
if (mydata.length <= 0) return "";
return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) {
return "<th>" + key + "</th>";
}).join("\n") + "</tr>").append($.map(mydata, function (index, value) {
return "<tr>" + $.map(index, function (val, key) {
return "<td>" + val + "</td>";
}).join("\n") + "</tr>";
}).join("\n"));
};

Categories