Related
I've a scenario where I've to iterate two list or arrays to get required values. So I am doing something like this:
var html = "";
$.each(list, function (i, set1) { //set1 is a list or array
$.each(set1.Tabs, function (i, set2) { //set1.Tabs is another one
html += "<li><a href='#" + set2.TabName + "'>" + set2.Details + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
})
})
The above works fine, it returns me the required data. But the problem is, say the outer loop has 10 values and the inner loop has four values. So the inner loop gets iterated ten times with the four values. This is natural and it should do. I was trying to get distinct values using the following (For the outer loop specifically):
list = list.filter((x, i, a) => a.indexOf(x) === i);
Though the above should work, my expected output is as follows:
Input: [1, 2, 3, 3, 4, 5, 6, 6]
Output: [1, 2, 3, 4, 5, 6]
N.B: My concern is with the inner loop, not with the outer one. But to iterate the inner loop, I've to go through the outer loop. Is there any way I can get the inner loop work directly?
Update 1: Sample Code
$(document).ready(function() {
var html = "";
var data = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" }
]
}
]
$.each(data, function(i, set1) { //set1 is a list or array
$.each(set1.topping, function(i, set2) { //set1.Tabs is another one
html += "<li><a href='#" + set2.id + "'>" + set2.type + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
})
})
$('#add').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add"></div>
You can create unique toppings based on the id and then render the list using unique toppings. To create unique toppings, you can use flatMap() Object.values() and array#reduce.
$(document).ready(function() {
var html = "";
var data = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
}
]
},
{
"id": "0002",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
}
]
}
]
const uniqueToppings = Object.values(data
.flatMap(o => o.topping)
.reduce((r, {id, type}) => {
r[id] = r[id] || {id, type};
return r;
},{}));;
$.each(uniqueToppings, function(i, set) {
html += "<li><a href='#" + set.id + "'>" + set.type + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
});
$('#add').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="add"></div>
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>
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>
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>
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 ) );
}