How to Display json data into html - javascript

I am trying to render the JSON data into HTML like this:
var data = [
{"id":"856","name":"India"},
{"id":"1035","name":"Chennai"},
{"id":"1048","name":"Delhi"},
{"id":"1113","name":"Lucknow"},
{"id":"1114","name":"Bangalore"},
{"id":"1115","name":"Ahmedabad"},
{"id":"1116","name":"Cochin"},
{"id":"1117","name":"London"},
{"id":"1118","name":"New York"},
{"id":"1119","name":"California"}
];
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#myDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
}
<table id="myDataTable">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</table>
But it doesn't work.

You are not calling your function drawTable(). Also you can use $.each() to loop data array
var data = [{
"id": "856",
"name": "India"
}, {
"id": "1035",
"name": "Chennai"
}, {
"id": "1048",
"name": "Delhi"
}, {
"id": "1113",
"name": "Lucknow"
}, {
"id": "1114",
"name": "Bangalore"
}, {
"id": "1115",
"name": "Ahmedabad"
}, {
"id": "1116",
"name": "Cochin"
}, {
"id": "1117",
"name": "London"
}, {
"id": "1118",
"name": "New York"
}, {
"id": "1119",
"name": "California"
}];
drawTable();
function drawTable() {
var table = $("#myDataTable");
$.each(data, function(index, rowData) {
table.append(
"<tr>"
+"<td>"+rowData.id+"</td>"
+"<td>"+rowData.name+"</td>"
+"</tr>"
);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myDataTable">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</table>

var data = [{
"id": "856",
"name": "India"
}, {
"id": "1035",
"name": "Chennai"
}, {
"id": "1048",
"name": "Delhi"
}, {
"id": "1113",
"name": "Lucknow"
}, {
"id": "1114",
"name": "Bangalore"
}, {
"id": "1115",
"name": "Ahmedabad"
}, {
"id": "1116",
"name": "Cochin"
}, {
"id": "1117",
"name": "London"
}, {
"id": "1118",
"name": "New York"
}, {
"id": "1119",
"name": "California"
}];
function drawRow(rowData) {
var table = document.getElementById('myDataTable');
for (var i = 0; i < rowData.length; i++) {
var tr = document.createElement('tr');
var td_1 = document.createElement('td');
var td_2 = document.createElement('td');
td_1.innerText = rowData[i].id;
td_2.innerText = rowData[i].name;
tr.appendChild(td_1);
tr.appendChild(td_2);
table.appendChild(tr);
}
}
drawRow(data);
<table id="myDataTable">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</table>

Related

How to display JSON data in a datatable using JavaScript - PHP code working but not sure how to convert to JavaScript

JSON Data not displaying as a header with column titles ColTitle, row for "Beginning Balance" and then row with ColData.
PHP code is working fine but its a new JavaScript based app I am working on.
This is the JavaScript code where I tried to get the table to appear
Mycontacts is actually a live JSON response but for the purpose of testing I put it on here.
<script type="text/javascript">
var myContacts = [
{
"Header": {
"Time": "2019-05-10T10:38:08-07:00",
"ReportName": "GeneralLedger",
"ReportBasis": "Accrual",
"StartPeriod": "2019-02-01",
"EndPeriod": "2019-02-01",
"Currency": "GBP",
"Option": [
{
"Name": "NoReportData",
"Value": "false"
}
]
},
"Columns": {
"Column": [
{
"ColTitle": "Date",
"ColType": "Date",
"MetaData": [
{
"Name": "ColKey",
"Value": "tx_date"
}
]
},
{
"ColTitle": "Transaction Type",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "txn_type"
}
]
},
{
"ColTitle": "No.",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "doc_num"
}
]
},
{
"ColTitle": "Name",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "name"
}
]
},
{
"ColTitle": "Customer",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "cust_name"
}
]
},
{
"ColTitle": "Supplier",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "vend_name"
}
]
},
{
"ColTitle": "Employee",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "emp_name"
}
]
},
{
"ColTitle": "Class",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "klass_name"
}
]
},
{
"ColTitle": "Product/Service",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "item_name"
}
]
},
{
"ColTitle": "Memo/Description",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "memo"
}
]
},
{
"ColTitle": "Account",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "account_name"
}
]
},
{
"ColTitle": "Debit",
"ColType": "Money",
"MetaData": [
{
"Name": "ColKey",
"Value": "debt_home_amt"
}
]
},
{
"ColTitle": "Credit",
"ColType": "Money",
"MetaData": [
{
"Name": "ColKey",
"Value": "credit_home_amt"
}
]
},
{
"ColTitle": "Amount",
"ColType": "Money",
"MetaData": [
{
"Name": "ColKey",
"Value": "subt_nat_home_amount"
}
]
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "1000 Bootcamp AMEX Acc",
"id": "134"
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Beginning Balance"
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total for 1000 Bootcamp AMEX Acc"
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
}
]
},
"type": "Section"
},
}
]
}
];
function generateDynamicTable(){
var noOfContacts = myContacts.length;
if(noOfContacts>0){
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
table.style.width = '50%';
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '0');
table.setAttribute('cellpadding', '5');
// retrieve column header ('Name', 'Email', and 'Mobile')
var col = []; // define an empty array
for (var i = 0; i < noOfContacts; i++) {
for (var key in myContacts[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.createElement("thead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.createElement("tr");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
hRow.appendChild(th);
}
tHead.appendChild(hRow);
table.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < noOfContacts; i++) {
var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD .
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
td.innerHTML = myContacts[i][col[j]];
bRow.appendChild(td);
}
tBody.appendChild(bRow)
}
table.appendChild(tBody);
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("myContacts");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
}
</script>
So in the above example I expected the first row of the table to have column headings, then a row for ColData - "value": "1000 Bootcamp AMEX Acc", then a row for ColData - "value": "Beginning Balance", then finally a row for ColData - "value": "Total for 1000 Bootcamp AMEX Acc".
This is just a sample - my live data is much larger than this so needed a loop for each of the Columns, Rows, Rows, Summary.
The below PHP coding seemed to work fine when using an SDK
echo "Report Name - " . $report['Header']['ReportName'];
echo "<br>";
echo "For Date: " . $report['Header']['DateMacro'] . " (".$report['Header']['StartPeriod']." - ".$report['Header']['EndPeriod'].")";
echo "<br>";
echo "Currency: " . $report['Header']['Currency'];
echo "<br>";
echo "<hr>";
echo '<table><thead>';
$NumberColumns = array();
echo '<th></th>';
// echo '<th>Account Name</th>';
$NumberColumns[]= ''; // get a foreach for number of cols if we need it
foreach ($report['Columns']['Column'] as $HeadKey => $columns) {
$NumberColumns[]= '';
echo '<th>';
echo $columns['ColTitle'];
if($columns['ColTitle'] == 'Credit') {
$CreditKey = $HeadKey;
}
echo '</th>';
}
echo '</thead><tbody>';
foreach($report['Rows']['Row'] as $MainRow) {
echo '<tr style="background-color:lightgrey">';
echo '<td><h3>' . $MainRow['Header']['ColData']['0']['value'] . '</h3></td>'; // SPLITTER ROW - SUMMARY
foreach ($MainRow['Summary']['ColData'] as $MainRowData) {
if ($counter++ == 0) continue;
echo '<td>' . $MainRowData['value'] . '</td>';
}
unset($counter);
echo '</tr>';
foreach($MainRow['Rows']['Row'] as $DetailRow) {
echo '<td></td>';
echo '</td>';
foreach($DetailRow['ColData'] as $DetailKey => $CellDetail) {
$CellContents = $CellDetail['value'];
if($DetailKey == $CreditKey) {
$CellContents = abs($CellDetail['value']) * -1;
}
echo '<td>' . $CellContents . '</td>';
}
echo '</tr>';
}
} // Main ROW
echo '</tbody></table>';
Some brackets got mixed up or were missing in myContacts Rows object. See comments in code sample.
The div with the id "myContacts" where you want to render your table, was not defined in your html markup. Here is the part where you call it:
var divContainer = document.getElementById("myContacts");
you defined your rendering function but forgot to call it initially:
generateDynamicTable() // TODO: call was missing at the end of your script
ADDITIONAL:
So you can use something like this for debugging purpose to get the right value :)
td.innerHTML = myContacts[i][col[j]]; // instead of this
td.innerHTML = JSON.stringify(myContacts[ i ][ col[ j ] ]); // use this
Hope I could help :)
Fiddle: https://jsfiddle.net/0xsf8qmg/
Here the Code:
var myContacts = [
{
"Header": {
"Time": "2019-05-10T10:38:08-07:00",
"ReportName": "GeneralLedger",
"ReportBasis": "Accrual",
"StartPeriod": "2019-02-01",
"EndPeriod": "2019-02-01",
"Currency": "GBP",
"Option": [
{
"Name": "NoReportData",
"Value": "false"
}
]
},
"Columns": {
"Column": [
{
"ColTitle": "Date",
"ColType": "Date",
"MetaData": [
{
"Name": "ColKey",
"Value": "tx_date"
}
]
},
{
"ColTitle": "Transaction Type",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "txn_type"
}
]
},
{
"ColTitle": "No.",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "doc_num"
}
]
},
{
"ColTitle": "Name",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "name"
}
]
},
{
"ColTitle": "Customer",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "cust_name"
}
]
},
{
"ColTitle": "Supplier",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "vend_name"
}
]
},
{
"ColTitle": "Employee",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "emp_name"
}
]
},
{
"ColTitle": "Class",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "klass_name"
}
]
},
{
"ColTitle": "Product/Service",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "item_name"
}
]
},
{
"ColTitle": "Memo/Description",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "memo"
}
]
},
{
"ColTitle": "Account",
"ColType": "String",
"MetaData": [
{
"Name": "ColKey",
"Value": "account_name"
}
]
},
{
"ColTitle": "Debit",
"ColType": "Money",
"MetaData": [
{
"Name": "ColKey",
"Value": "debt_home_amt"
}
]
},
{
"ColTitle": "Credit",
"ColType": "Money",
"MetaData": [
{
"Name": "ColKey",
"Value": "credit_home_amt"
}
]
},
{
"ColTitle": "Amount",
"ColType": "Money",
"MetaData": [
{
"Name": "ColKey",
"Value": "subt_nat_home_amount"
}
]
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "1000 Bootcamp AMEX Acc",
"id": "134"
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Beginning Balance"
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total for 1000 Bootcamp AMEX Acc"
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
},
{
"value": ""
}
]
},
"type": "Section"
},
] // TODO: this one was missing
}
// ] TODO: this one is accidentally
}
];
function generateDynamicTable(){
var noOfContacts = myContacts.length;
if(noOfContacts>0){
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
table.style.width = '50%';
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '0');
table.setAttribute('cellpadding', '5');
// retrieve column header ('Name', 'Email', and 'Mobile')
var col = []; // define an empty array
for (var i = 0; i < noOfContacts; i++) {
for (var key in myContacts[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.createElement("thead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.createElement("tr");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
hRow.appendChild(th);
}
tHead.appendChild(hRow);
table.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < noOfContacts; i++) {
var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD .
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
// td.innerHTML = JSON.stringify(myContacts[ i ][ col[ j ] ]); // TODO: for debugging purpose instead of the following line
td.innerHTML = myContacts[i][col[j]];
bRow.appendChild(td);
}
tBody.appendChild(bRow)
}
table.appendChild(tBody);
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("myContacts");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
}
generateDynamicTable() // TODO: call was missing
<div id="myContacts"></div>

Issue on Loading JSON to HTML Table Properly

I am trying to load a JSON data to an HTML table which the desired output shuld looks like
but I am getting this in my try
Here is my try
var data = {
"action":
[
{ "id": "1001", "type": "Matrix" },
{ "id": "1002", "type": "IP Man" },
{ "id": "1003", "type": "Revenge" }
],
"comedy":
[
{ "id": "2001", "type": "Iceman" },
{ "id": "2002", "type": "Pat & Mat" },
{ "id": "2003", "type": "Sugar" }
],
"animation":
[
{ "id": "3001", "type": "Frozen" },
{ "id": "3002", "type": "Tangled" },
{ "id": "3003", "type": "Croods" }
]
};
for (var i in data) {
$('#result').append('<table class="table table-striped"><thead><tr><th>Id</th><th>Type</th></tr></thead><tbody class="map"></tbody></table>');
}
var tds = '<tr>';
for (var j = 0; j < data[i].length; j++) {
var obj = data[i][j];
tds += '<td>' + obj.id + '</td>';
tds += '<td>' + obj.type + '</td>';
}
$('.map').append(tds);
body {
background: white;
}
table {
margin: 10px;
border: 2px solid #eee;
}
td {
margin: 10px;
border: 2px solid #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Can you please let me know how I can fix this?
First problem: you had opened a tr element, but hadn’t closed it. Second problem: you were analyzing only the last “category” (animation).
var data = {
"action": [
{ "id": "1001", "type": "Matrix" },
{ "id": "1002", "type": "IP Man" },
{ "id": "1003", "type": "Revenge" }
],
"comedy": [
{ "id": "2001", "type": "Iceman" },
{ "id": "2002", "type": "Pat & Mat" },
{ "id": "2003", "type": "Sugar" }
],
"animation": [
{ "id": "3001", "type": "Frozen" },
{ "id": "3002", "type": "Tangled" },
{ "id": "3003", "type": "Croods" }
]
};
var result = $('#result');
for (var category in data) {
result.append(
'<table class="table table-striped"><thead>' +
'<tr><th>Id</th><th>Type</th></tr>' +
'</thead><tbody id="map_' + category + '"></tbody></table>'
);
for (var i = 0; i < data[category].length; ++ i) {
var item = data[category][i];
$('#map_' + category).append(
'<tr><td>' + item.id + '</td><td>' + item.type + '</td></tr>'
);
}
}
You are not closing off the row in the for loop.
You need to include the and elements in the loop too because you are adding rows, not cells.
var data = {
"action":
[
{ "id": "1001", "type": "Matrix" },
{ "id": "1002", "type": "IP Man" },
{ "id": "1003", "type": "Revenge" }
],
"comedy":
[
{ "id": "2001", "type": "Iceman" },
{ "id": "2002", "type": "Pat & Mat" },
{ "id": "2003", "type": "Sugar" }
],
"animation":
[
{ "id": "3001", "type": "Frozen" },
{ "id": "3002", "type": "Tangled" },
{ "id": "3003", "type": "Croods" }
]
};
var keys = Object.keys(data);
keys.forEach((key) => {
$('#result').append('<table class="table table-striped"><thead><tr><th>Id</th><th>Type</th></tr></thead><tbody class="map" id="'+key+'" ></tbody></table>');
data[key].forEach((obj) =>{
$('#'+key).append("<tr><td>"+obj.id+"</td><td>"+obj.type+"</td></tr>");
})
})
body {
background: white;
}
table {
margin: 10px;
border: 2px solid #eee;
}
td {
margin: 10px;
border: 2px solid #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

String not being appended in function

I am trying to parse a JSON and build a HTML string to append to the DOM but no matter what I do the string is only returning the first element in the JSON.
Here's the js:
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
var test_html = "<ul>",
buildNavHelper = function(curNode){
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
};
buildNavHelper(menu_json);
test_html += "</ul>";
$('#thing').append(test_html);
Heres a fiddle
https://jsfiddle.net/w734bvw7/
buildNavHelper() has no return statement, so there's nothing coming back from _.map(). The outer test_html isn't in scope. Try this:
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
test_html = "<ul>" + buildNavHelper(menu_json) + "</ul>";
Note the addition of .join() to avoid having commas in your output.
Also, there's no need to use underscore here; Array.map() is native Javascript.
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + curNode.children.map(buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
https://jsfiddle.net/w734bvw7/3/
buildNavHelper = function(curNode){
var test_html = "<ul>";
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
test_html += "</ul>";
return test_html;
};
$('#thing').append(buildNavHelper(menu_json));
Building the list using HTML strings can produce HTML injection. I recommend DOM methods instead:
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
document.querySelector('#thing').appendChild(buildNavHelper([menu_json]));
<div id="thing"></div>

Loop within a loop indexes

I'm building a HTML table using JSON to populate it.
Here's the JSON:
{
"grid": {
"name": "JsonGrid",
"columns": [
{
"name": "ID",
"width": "100px"
},
{
"name": "Name",
"width": "100%"
},
{
"name": "Departments",
"width": "250px"
},
{
"name": "Locations",
"width": "250px"
}
]
},
"data": [
{
"id": 1,
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
},
{
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
},
{
"id": 3,
"name": "Company C",
"departments": [
"Medical",
"Family",
"Criminal"
],
"locations": [
"Sheffield",
"Rotherham"
]
}
]
}
and the function that loops through the data object:
function addDataFromJson(json)
{
var data = json.data;
for(var i=0;i<data.length;i++) // for each row
{
var columns = '';
for(var b=0;b<Object.keys(data[i]).length;b++) // for each column
{
var content = data[i][b];
console.log(content);
columns += '<td>'+content+'</td>';
}
var row = columns;
$( '<tr>' + row + '</tr>' ).appendTo('.uiGridContent tbody').hide().fadeIn();
}
}
So I loop through to get the rows and look inside to find what columns I need, and then try and put the data into each column and then append the row. The columns and rows are perfect, but the data never gets pulled out!
It looks like I'm getting confused as I step into the second loop that pulls the actual data for each column. What should the content variable contain? Taking into consideration that sometimes the content may contain arrays instead of just strings.
The problem is the use of b, it is just an index of the key not the actual property key so you need
var content = data[i][Object.keys(data[i])[b]];
like
var json = {
"grid": {
"name": "JsonGrid",
"columns": [{
"name": "ID",
"width": "100px"
}, {
"name": "Name",
"width": "100%"
}, {
"name": "Departments",
"width": "250px"
}, {
"name": "Locations",
"width": "250px"
}]
},
"data": [{
"id": 1,
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
}, {
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
}, {
"id": 3,
"name": "Company C",
"departments": [
"Medical",
"Family",
"Criminal"
],
"locations": [
"Sheffield",
"Rotherham"
]
}]
};
function addDataFromJson(json) {
var data = json.data;
for (var i = 0; i < data.length; i++) // for each row
{
var columns = '',
keys = Object.keys(data[i]);
for (var b = 0; b < keys.length; b++) // for each column
{
var content = data[i][keys[b]];
console.log(content);
columns += '<td>' + content + '</td>';
}
var row = columns;
$('<tr>' + row + '</tr>').appendTo('.uiGridContent tbody').hide().fadeIn();
}
}
addDataFromJson(json)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="uiGridContent">
<tbody></tbody>
</table>
A more simpler way will be
var json = {
"grid": {
"name": "JsonGrid",
"columns": [{
"name": "ID",
"width": "100px"
}, {
"name": "Name",
"width": "100%"
}, {
"name": "Departments",
"width": "250px"
}, {
"name": "Locations",
"width": "250px"
}]
},
"data": [{
"id": 1,
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
}, {
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
}, {
"id": 3,
"name": "Company C",
"departments": [
"Medical",
"Family",
"Criminal"
],
"locations": [
"Sheffield",
"Rotherham"
]
}]
};
function addDataFromJson(json) {
var data = json.data;
var rows = $.map(data, function(record) {
var cols = $.map(record, function(value, key) {
return '<td>' + value + '</td>';
})
return '<tr>' + cols + '</tr>';
})
$(rows.join('')).hide().appendTo('.uiGridContent tbody').fadeIn();
}
addDataFromJson(json)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="uiGridContent">
<tbody></tbody>
</table>
Better use ECMAScript 5.1 helpers for better understanding what your code makes:
function addDataFromJSON(json) {
//just check that data is array
var data = json && Array.isArray(json.data) ? json.data : [];
data.forEach(function(rowObject) {
//every loop will create a row
var tr = document.createElement('tr');
Object.keys(rowObject).forEach(function(cellKey) {
//every loop will create a cell
var td = document.createElement('td');
td.innerText = rowObject[cellKey];
tr.appendChild(td);
});
table.appendChild(tr);
});
}
var table = document.querySelector('#table');
var jsonData = {
"data": [{ //this is row
"id": 1, // this is a cell value
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
}, { //this is one more row
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
}]
};
function addDataFromJSON(json) {
//just check that data is array
var data = json && Array.isArray(json.data) ? json.data : [];
data.forEach(function(rowObject) {
//every loop will create a row
var tr = document.createElement('tr');
Object.keys(rowObject).forEach(function(cellKey) {
//every loop will create a cell
var td = document.createElement('td');
td.innerText = rowObject[cellKey];
tr.appendChild(td);
});
table.appendChild(tr);
});
}
addDataFromJSON(jsonData);
table,
td {
border: 1px solid #ccc;
border-spacing: 0;
border-collapse: collapse;
}
td {
padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table id=table></table>
</body>
</html>

Json Nested Object Array to Table

I have a json file, there is an array of objects. In the first object is a 2nd array with +/- 200 objects. Is there a possibility to show the 2nd array in a new table in the last row of the first table?
As seen here, there should be a nested table in the column: "Friends"
http://jsfiddle.net/TqbMC/
The html is:
<body onLoad="buildHtmlTable()">
<table id="excelDataTable" border="1">
</table>
</body>
The rest of the code is:
var myList=[{
"id": "220439",
"name": "Bret Taylor",
"friends": {
"data": [
{
"id": "100003461417780",
"name": "Pedro Fernandes"
},
{
"id": "100004448132997",
"name": "Tatiane Rodrigues"
},
{
"id": "100002608573875",
"name": "Gerson Yoody"
},
{
"id": "100003532942622",
"name": "Brennen Roup"
},
{
"id": "100003910478450",
"name": "Maruxita Gomez"
},
{
"id": "100003035179424",
"name": "Ekta Vaghasia"
},
{
"id": "100003034655176",
"name": "Nikita Adam"
},
{
"id": "100004269720826",
"name": "Lukas Ks"
},
{
"id": "100004489472386",
"name": "Hong Finozaza"
},
{
"id": "1436623789",
"name": "Dianita M Ct"
},
{
"id": "100004324535652",
"name": "Ana Paula"
},
{
"id": "100004433135086",
"name": "Caroline Geovannini"
},
{
"id": "100004081013147",
"name": "Ryan Bispo Silva"
},
{
"id": "1697844686",
"name": "Louann Hyatt Clark"
},
{
"id": "100003283377051",
"name": "Ysabel Salazar"
},
{
"id": "100003398360349",
"name": "Ty SoHigh Walker"
},
{
"id": "100001201489463",
"name": "Dicu Andrei D"
},
{
"id": "100001811128458",
"name": "Cristy Torres Castellanos"
},
{
"id": "1693121601",
"name": "Jasim Amit"
},
{
"id": "100001966217366",
"name": "Candy Chhokar"
},
{
"id": "100004096284395",
"name": "Stefania Bilska"
},
{
"id": "100004084157244",
"name": "Papah Noval"
},
{
"id": "1791202672",
"name": "Bianca Agostina Gherardini"
},
{
"id": "100000825894241",
"name": "Usman Faiz"
},
{
"id": "100002424916440",
"name": "Muhammad Tajminur Rahman"
}
],
"paging": {
"next": "https://graph.facebook.com/99394368305/likes?limit=25&after=MTAwMDAyNDI0OTE2NDQw"
}
}
}];
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable() {
var columns = addAllColumnHeaders(myList);
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").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(myList)
{
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1){
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
(the data comes from the facebook graph api)
you can access inner data in this way: myList[0].friends.data[i].id and myList[0].friends.data[i].name, just iterate until myList[0].friends.data.length is reached and build whatever structure you want - for example create table row for each friend with two td - one for id and one for name – magyar1984
http://jsfiddle.net/6v8Ew/1/
for (var x = 0 ; x < myList[0].friends.data.length ; x++){
$line.append( $( "<td></td>" ).html( myList[0].friends.data[x].id ) );
}

Categories

Resources