Related
I'm looping an object and expect the result as elements of a table
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
},
pp_ = '<table><tbody>';
for (var i in db) {
if (db.hasOwnProperty(i)) {
var js = db[i].split(',');
for (var x in js) {
if (i.startsWith('pp_')) {
pp_ += '<tr><td>' + i + ' ' + x + ' : ' + js[x] + '</td></tr>';
}
}
}
}
pp_ += '</tbody></table>';
document.write(pp_);
I am splitting values that have commas so that each index of an array sits on 1 row (tr)
what I can't figure out is how to place elements with the same index on the same level (row) so I can I have something like
table, td {
border: 1px solid black;
}
<table>
<tbody>
<tr>
<td> pp_flavour 0 - its value </td>
<td> pp_fruit_batch 0 - its value </td>
</tr>
<tr>
<td> pp_flavour 1 - its value </td>
<td> pp_fruit_batch 1 - its value </td>
</tr>
<tr>
<td> pp_flavour 2 - its value </td>
<td> pp_fruit_batch 2 - its value </td>
</tr>
</tbody>
</table>
<br>
<table>
<tbody>
<tr>
<td> sl_favour 0 - its value </td>
<td> sl_appearance 0 - its value </td>
</tr>
<tr>
<td> sl_favour 1 - its value </td>
<td> sl_appearance 1 - its value </td>
</tr>
</tbody>
</table>
and so on...
You could try indexing the database like this:
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
};
var prefixes = ["pp", "ht", "sl"];
var prefixedDb = {};
var result = "";
for (var i in db) {
if (db.hasOwnProperty(i)) {
var parts = i.split("_");
var prefix = parts[0];
if (prefixes.indexOf(prefix) === -1) continue;
if (prefixedDb[prefix] === undefined) {
prefixedDb[prefix] = {};
}
prefixedDb[prefix][parts.slice(1).join("_")] = db[i];
}
}
for (var k in prefixedDb) {
if (prefixedDb.hasOwnProperty(k)) {
var db = prefixedDb[k];
var dbIndexed = {};
for (var i in db) {
if (db.hasOwnProperty(i)) {
var vals = db[i].split(',');
vals.forEach(function(val, j) {
if (dbIndexed[j] === undefined) {
dbIndexed[j] = {};
}
dbIndexed[j][i] = val;
});
}
}
result += "<table><tbody>";
for (var i in dbIndexed) {
if (dbIndexed.hasOwnProperty(i)) {
result += "<tr>";
var indexVals = dbIndexed[i];
for (var j in indexVals) {
if (indexVals.hasOwnProperty(j)) {
result += "<td>" + j + " " + i + " - " + indexVals[j] + "</td>";
}
}
result += "</tr>";
}
}
result += "</tbody></table>";
}
}
document.write(result);
table, td {
border: 1px solid black;
}
Please note that this code may not be the most optimized code for this task.
You can try adding each value of the table to a 2-D array and than form the table from this 2-D array
try below solution
NOTE: this will also work with different number of rows and Column.
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
};
function createTable(myKey){
var rows = [];
for (var dbKey in db) {
if (db.hasOwnProperty(dbKey)) {
if (dbKey.startsWith(myKey)) {
var values = db[dbKey].split(',');
for (var val in values) {
if (!rows[val])
rows[val] = [];
rows[val].push('<td>' + dbKey + ' ' + val + ' : ' + values[val] + '</td>');
}
}
}
}
var myTable = '<table><tbody>';
for (var i = 0; i < rows.length; i++) {
myTable += "<tr>" + rows[i].join("") + "</tr>";
}
myTable += '</tbody></table>';
return myTable;
}
var ht_table = createTable("ht_");
document.getElementById("myTable").innerHTML +="<br/>"+ ht_table;
var pp_table = createTable("pp_");
document.getElementById("myTable").innerHTML +="<br/>"+ pp_table;
var sl_table = createTable("sl_");
document.getElementById("myTable").innerHTML += "<br/>"+ sl_table;
table, td {
border-style: solid;
}
<p id="myTable">
</p>
You could take the wanted values out of the object, split them and take the max length for iterating the rows for the table. Then assemble the table by iterating the values.
var db = { pp_flavour: "ytv,yurtcrc,urt", pp_fruit_batch: "cuyt,cytc,yt,42" },
values = Object.keys(db).filter(k => k.startsWith('pp_')).map(k => (db[k] || '').split(',')),
length = values.reduce((r, a) => Math.max(r, a.length), 0),
table = document.createElement('table'),
tr,
i;
for (i = 0; i < length; i++) {
tr = document.createElement('tr');
table.appendChild(tr);
values.forEach(function (a) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(i in a ? a[i] : ''));
tr.appendChild(td);
});
}
document.body.appendChild(table);
Create a loop, incrementing a counter, which will determine if a key's split value should be output.
If there are no more values found at the index of the counter, stop looping.
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
},
s = '';
['pp_', 'ht_', 'sl_'].forEach(function(type) {
var i,
found = true;
s += '<table>';
for(i = 0 ; found ; i++) {
s += '<tr>';
found = false;
Object.keys(db).forEach(function(key) {
var js = db[key].split(',');
if(js[i] && key.startsWith(type)) {
found = true;
s += '<td>' + key + ' ' + i + ' : ' + js[i] + '</td>';
}
});
s += '</tr>';
}
s += '</table>';
});
document.write(s);
td {
border-bottom: 1px solid #bbb;
border-right: 1px solid #ddd;
padding: 0.5em;
}
table {
border: 1px solid black;
margin-bottom: 1em;
border-spacing: 0;
}
Hello everyone I'm trying to get table data in json format here is my table
<table>
<thead>
<tr>
<th>srno</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jhon One</td>
<td>Doe one</td>
</tr>
<tr>
<td>2</td>
<td>Jhon two</td>
<td>Doe Two</td>
</tr>
</tbody>
</table>
<button>
convert
</button>
the result which i am getting is this
{
"0": {
"1",
"Jhon One",
"Doe one"
}
,
"1": {
"2",
"Jhon two",
"Doe Two"
}
}
using the below javascript
$("button").click(function() {
var json = html2json();
alert(json);
});
function html2json() {
var json = '{';
var otArr = [];
// var i = 1;
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
x.each(function() {
itArr.push('"' + $(this).text() + '"');
});
otArr.push('"' + e + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
return json;
}
but i want to add key to every value and the number should start from one and not zero.
i have a set of desire result and it should look like this
any help is appreciated
{
"1": {
no: "1",
name:"Jhon One",
lastname "Doe one"
}
,
"2": {
no: "1",
name:"Jhon two",
lastname "Doe two"
}
}
here is the fiddel link which i have tried
https://jsfiddle.net/k228n2bn/
Just change the following line
otArr.push('"' + e + '": {' + itArr.join(',') + '}');
to
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
The parenthesis will add the values as numbers not strings.
Also, add keys array for internal object keys.
function html2json() {
var json = '{';
var otArr = [];
// var i = 1;
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
var keys = ['no','name','lastname'];
x.each(function(i) {
itArr.push('"' + keys[i] + '":"' + $(this).text() + '"');
});
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
return json;
}
You can convert e to a Number and add one to it like in this fiddle.
function html2json() {
var json = '{';
var otArr = [];
// var i = 1;
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
x.each(function() {
itArr.push('"' + $(this).text() + '"');
});
otArr.push('"' + (Number(e) + 1) + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
return json;
}
The json you're returning is not valid though. You may want to do something like this fiddle if you can to simplify and ensure valid json and to create your objects from any table structure.
function html2json() {
var otArr = [];
var tblHeaders = Array.from($('table thead tr')
.children())
.map(header => $(header).text());
var tbl2 = $('table tbody tr').each(function(e) {
const values = Array.from($(this).children());
const row = {};
for (let i = 0; i < tblHeaders.length; i++){
row[tblHeaders[i]] = $(values[i]).text();
}
otArr.push({
[e+1]: row
})
})
json = JSON.stringify(otArr);
return json;
}
Try e+1
change otArr.push('"' + e + '": {' + itArr.join(',') + '}');
to
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
$("button").click(function() {
var json = html2json();
});
function html2json() {
var json = '{';
var otArr = [];
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
x.each(function(e) {
var items='';
if(e == 0){
items +='no : "'+ $(this).text()+'"';
}
if(e == 1){
items +='name : "' +$(this).text()+'"';
}
if(e == 2){
items +='email : "' +$(this).text()+'"';
}
itArr.push(items);
});
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
alert(json);
return json;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>srno</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jhon One</td>
<td>Doe one</td>
</tr>
<tr>
<td>2</td>
<td>Jhon two</td>
<td>Doe Two</td>
</tr>
</tbody>
</table>
<button>
convert
</button>
Maybe you can use theads as keys for the generated objects.
Check this jsfiddle.
function html2json() {
var $table = $('table');
var $ths = $table.find('thead>tr>th');
var rows = {};
$table.find('tbody>tr').each(function () {
var row = {};
$(this).children().each(function (index) {
row[$ths[index].textContent] = this.textContent;
});
rows[row.srno] = row;
});
return JSON.stringify(rows);
}
i have a 2d array like this
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
But in html i want to render this array like
**Names** **Numbers**
alex => 2,4,6
jhon => 11,13
You can use reduce() to return object and then Object.keys() and forEach loop to add to HTML
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
var result = items.reduce(function(r, e) {
r[e[0]] = (r[e[0]] || []).concat(e[1]);
return r;
}, {});
var rows = '';
Object.keys(result).forEach(function(e) {
rows += '<tr><td>' + e + '</td><td>' + result[e].join(',') + '</td></tr>';
});
document.querySelector('table tbody').innerHTML += rows;
<table>
<tbody>
<tr><td>Names</td><td>Numbers</td></tr>
</tbody>
</table>
Instead of reduce and array grouping I propose a jQuery approach (this is not the best solution but only a different point of view):
$(function () {
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
$.each(items, function(indexInArray, value) {
var cellIfExist = $('#result').find('td:contains(' + value[0] + ')');
if (cellIfExist.length > 0) {
cellIfExist.next().text(cellIfExist.next().text() + ', ' + value[1]);
} else {
$('#result').append('<tr><td>' + value[0] + '</td><td>' + value[1] + '</td></tr>')
}
});
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<table id="result">
<tr>
<td>**Names**</td>
<td>**Numbers**</td>
</tr>
</table>
well the old-school way is probably to iterate over the array and while doing so build an object that's pretty much like an associative array.
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
var group = { }
for(var i = 0; i < items.length; i++) {
var pair = items[i];
if(group[pair[0]]) {
group[pair[0]].push(pair[1]);
}
else {
group[pair[0]] = [pair[1]];
}
}
"group" is then your grouped object. Iterate over it using a for-loop.
Simple solution using Array.forEach function:
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]],
names = {};
items.forEach(function (arr) {
(names[arr[0]])? names[arr[0]].push(arr[1]) : (names[arr[0]] = [arr[1]]);
});
console.log(JSON.stringify(names, 0, 4));
Hi I have a jquery scripts that takes table template and adds N rows (N=[1...100]) as clones of first TR. then each cell in each row is populated with some data (not all cells are always filled), each cell has " on clik " event attached, and on cell hover row, cell, coll is highlighted.
The problem i am facing is the optimization of generation (time) and usability (the mouse movemnts aren't smooth)
the code:
HTML template table:
<table id='schedulerview' class='myGrid'>
<colgroup id='col_0'></colgroup>
<colgroup id='col_1'></colgroup>
<colgroup id='col_2'></colgroup>
<colgroup id='col_3'></colgroup>
....
<colgroup id='col_55'></colgroup>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
....
<th>51</th>
</tr>
</thead>
<tbody>
<tr id='template' style='display:none'>
<td id='0' HID='W0_Y_I' class='scheddata'>Week 1</td>
.....
<td id='51' HID='W55_Y_I' class='scheddata'>Week 52</td>
</tr>
</tbody>
</table>
CSS :
.litrow { background-color: #eee; }
.litcell { background-color: yellow; }
file codebehind.js
$(document).ready(function () {
//turn on row, cell, column highlight on hover
$("table#schedulerview tbody").on('mouseenter', 'tr', function () {
$(this).addClass('litrow');
});
$("table#schedulerview tbody").on('mouseleave', 'tr', function () {
$(this).removeClass('litrow');
});
$("table#schedulerview tbody").on('mouseenter', 'td', function () {
$(this).addClass('litcell');
$("colgroup").eq($(this).index()).addClass("litrow");
});
$("table#schedulerview tbody").on('mouseleave', 'td', function () {
$(this).removeClass('litcell');
$("colgroup").eq($(this).index()).removeClass("litrow");
});
//function for getting data and create schedule table from template table
getSchedule();
});
getschedule function:
function getSchedule() {
var data = "{userid:'" + userid + "',year:" + year + "}";
$.ajax({
type: "POST",
url: "/Scheduler.aspx/getSchedule",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (ret) {
var areas = JSON.parse(ret.d.Areas);
var schedule = JSON.parse(ret.d.Schedule);
//remove all rows from table that are not template
$('table#schedulerview tr.eventSchedule').remove();
//create row for each element from DB - prepare matrix elementsXWeeks
var $tr = $('#template');
$.each(areas, function (i, x) {
var $clone = $tr.clone();
$clone.css('display', 'block');
$clone.attr('id', 'new_row_' + i);
$clone.addClass('eventSchedule');
$clone.children('td:first').text(x.AreaName);
//for each cell in new row
$clone.children('td.scheddata').each(function () {
var $this = $(this);
var HID = $this.attr("HID").replace('_Y_', '_' + year + '_').replace('_I', '_' + x.IDObszaru);
$this.attr("HID", HID);
});
$tr.before($clone);
});
//fill in the matrix with scheduled data
$.each(schedule, function (i, x) {
$td = $("table#schedulerview td[HID='" + x.HID + "']");
$td.addClass(x.Status);
$td.attr("WeekNum", x.WeekNum);
$td.attr("PlanID", x.Id);
$td.parent().addClass('plannedrow');
});
},
error: function (ret) {
alert(ret.responseText);
}
});
}
The getSchedule() function lasts few seconds, is it possible to optimize it so it would be faster?
CHANGES:
I've tried different approach for row creation:
for (i = 0; i < areas.length; i++) {
$lasttr = $("table#schedulerview tbody").append("<tr id='new_row_" + i + "' class='eventSchedule' ></tr>");
$lasttr = $("table#schedulerview tbody tr#new_row_" + i);
for (j = 0; j < 56; j++) {
var sclass = "";
if (j == 0)
$lasttr.append("<td>" + areas[i].AreaName + "</td>");
if (j == 1)
$lasttr.append("<td>" + areas[i].AreaSubName + "</td>");
if (j == 2)
$lasttr.append("<td>" + areas[i].AreaParentName + "</td>");
if (j > 2) {
sclass = "'scheddata'";
k = j - 2;
$lasttr.append("<td class=" + sclass + " HID='W" + k + "_" + year + "_" + areas[i].AreaID + "'></td>");
}
}
}
but it's not fast enough- and the problem with hovering remains. (also when using css :hover pseudoclass.
Can you do something like this?
$(function () {
for (i = 0; i < 56; i++)
$("thead tr").append("<th>" + (i+1) +"</th>");
for (i = 0; i < 20; i++){
$("tbody").append("<tr />");
for (j = 0; j < 56; j++)
$("tbody tr:last-child").append("<td>" + ((i+1) + ": " + (j+1)) +"</td>");
}
});
table tr:hover td {background: #99f;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<thead><tr></tr></thead>
<tbody></tbody>
</table>
I am trying to display a "leaderboard" table based on JSON data.
I have read a lot about the JSON format and overcome some initial obstacles, but my Javascript knowledge is very limited and I need help!
Basically my JSON data comes through looking like this:
[{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}]
What I need is to be able to loop through this array, generating a table row or list item for each object. There will be an unknown amount of total objects in the array but each will have the same format- three values: Name, Score, Team.
So far I have used the following code, which confirms that I am successfully loading the objects in the console-
$.getJSON(url,
function(data){
console.log(data);
});
but I am not sure how to iterate over them, parsing them into the HTML table.
The next step is sorting the entries by score in descending order...
Any help would be much appreciated.
Thanks!
EDIT:
Updated code below, this works:
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
}
});
(The $.parseJSON was not necessary, we can use 'data' as the JSON array is already parsed I believe)
Loop over each object, appending a table row with the relevant data each iteration.
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
}
});
});
JSFiddle
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","score":"30"},{"name": "name2","score":"50"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<div jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{score}}</td>
</tr>
</div>
<table>
<tbody id="tbody">
</tbody>
</table>
Loop over each object, push in string array and join them. Append in target table, it is better.
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr=[];
for (var i = 0; i < json.length; i++) {
tr.push('<tr>');
tr.push("<td>" + json[i].User_Name + "</td>");
tr.push("<td>" + json[i].score + "</td>");
tr.push("<td>" + json[i].team + "</td>");
tr.push('</tr>');
}
$('table').append($(tr.join('')));
});
You can use KnockoutJS with jQuery. KnockoutJS have smart data-binding features. By using the foreach binding feature you can write your code like this example:
HTML:
<table>
<thead>
<tr>
<th>User Name</th>
<th>Score</th>
<th>Team</th>
</tr>
</thead>
<tbody data-bind="foreach: teams">
<tr>
<td data-bind="text: User_Name"></td>
<td data-bind="text: score "></td>
<td data-bind="text: team "></td>
</tr>
</tbody>
</table>
JavaScript:
$(document).ready(function () {
$.getJSON(url,function (json) {
ko.applyBindings({
teams: json
});
}
});
});
Fiddle Demo with your dummy data
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
This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
Example:
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='myDiv'>table goes here</div>
another nice recursive way to generate HTML from a nested JSON object (currently not supporting arrays):
// generate HTML code for an object
var make_table = function(json, css_class='tbl_calss', tabs=1){
// helper to tabulate the HTML tags. will return '\t\t\t' for num_of_tabs=3
var tab = function(num_of_tabs){
var s = '';
for (var i=0; i<num_of_tabs; i++){
s += '\t';
}
//console.log('tabbing done. tabs=' + tabs)
return s;
}
// recursive function that returns a fixed block of <td>......</td>.
var generate_td = function(json){
if (!(typeof(json) == 'object')){
// for primitive data - direct wrap in <td>...</td>
return tab(tabs) + '<td>'+json+'</td>\n';
}else{
// recursive call for objects to open a new sub-table inside the <td>...</td>
// (object[key] may be also an object)
var s = tab(++tabs)+'<td>\n';
s += tab(++tabs)+'<table class="'+css_class+'">\n';
for (var k in json){
s += tab(++tabs)+'<tr>\n';
s += tab(++tabs)+'<td>' + k + '</td>\n';
s += generate_td(json[k]);
s += tab(--tabs)+'</tr>' + tab(--tabs) + '\n';
}
// close the <td>...</td> external block
s += tab(tabs--)+'</table>\n';
s += tab(tabs--)+'</td>\n';
return s;
}
}
// construct the complete HTML code
var html_code = '' ;
html_code += tab(++tabs)+'<table class="'+css_class+'">\n';
html_code += tab(++tabs)+'<tr>\n';
html_code += generate_td(json);
html_code += tab(tabs--)+'</tr>\n';
html_code += tab(tabs--)+'</table>\n';
return html_code;
}
Here are two ways to do the same thing, with or without jQuery:
// jquery way
$(document).ready(function () {
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').first().append(tr);
}
});
// without jquery
function ready(){
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];
const table = document.getElementsByTagName('table')[1];
json.forEach((obj) => {
const row = table.insertRow(-1)
row.innerHTML = `
<td>${obj.User_Name}</td>
<td>${obj.score}</td>
<td>${obj.team}</td>
`;
});
};
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
ready();
} else {
document.addEventListener('DOMContentLoaded', ready);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>User_Name</th>
<th>score</th>
<th>team</th>
</tr>
</table>'
<table>
<tr>
<th>User_Name</th>
<th>score</th>
<th>team</th>
</tr>
</table>
I spent a lot of time developing various reports. So, now I have an idea - create a web framework for building web reports. I have started here:
https://github.com/ColdSIce/ReportUI
Now it is an angular 4 module. You can pass your json data to TableLayoutComponent and get a HTML table as result. Table already has fixed header. Also you can fix some your columns by default or by click. More there, you can customize table properties like background-color, font-color, row-height etc.
If you are interested you can join me in this project and help.
Here is an another way to parse json object into Html table
//EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < d.length; i++) {
for (var key in d[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");// TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < d.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = d[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
This code will help a lot
function isObject(data){
var tb = document.createElement("table");
if(data !=null) {
var keyOfobj = Object.keys(data);
var ValOfObj = Object.values(data);
for (var i = 0; i < keyOfobj.length; i++) {
var tr = document.createElement('tr');
var td = document.createElement('td');
var key = document.createTextNode(keyOfobj[i]);
td.appendChild(key);
tr.appendChild(td);
tb.appendChild(tr);
if(typeof(ValOfObj[i]) == "object") {
if(ValOfObj[i] !=null) {
tr.setAttribute("style","font-weight: bold");
isObject(ValOfObj[i]);
} else {
var td = document.createElement('td');
var value = document.createTextNode(ValOfObj[i]);
td.appendChild(value);
tr.appendChild(td);
tb.appendChild(tr);
}
} else {
var td = document.createElement('td');
var value = document.createTextNode(ValOfObj[i]);
td.appendChild(value);
tr.appendChild(td);
tb.appendChild(tr);
}
}
}
}
For those interested in a general solution in plain Vanilla JS. It works independently of the number of columns you have in your json.
const myData = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}]
const createTable = (json) => {
let table = document.getElementById('js-table')
for (let row of json) {
let newRow = table.insertRow();
for (let cell of Object.values(row)) {
let newCell = newRow.insertCell();
let newText = document.createTextNode(cell);
newCell.appendChild(newText);
}
}
}
createTable(myData)
<table>
<tbody id="js-table">
</tbody>
</table>
This post is very much helpful to all of you
First Parse the json data by using jquery eval parser and then iterarate through jquery each function below is the code sniplet:
var obj = eval("(" + data.d + ")");
alert(obj);
$.each(obj, function (index,Object) {
var Id = Object.Id;
var AptYear = Object.AptYear;
$("#ddlyear").append('<option value=' + Id + '>' + AptYear + '</option>').toString();
});