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>
Related
Please help
I tried to edit the second myArray, and in myArray there is myArray[data] which is also an array, how do I update it??
var myArray= [
{
"id": 0,
"item": "DONOMULYO",
"data": [
{
"id": 0,
"field": "satu",
"record": "11"
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
},
{
"id": 1,
"item": "PAGAK",
"data": [
{
"id": 0,
"field": "satu",
"record": "11"
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
},
{
**"id": 2,**
"item": "BANTUR",
"data": [
{
"id": 0,
"field": "satu",
**"record": "11"**
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
},
{
"id": 3,
"item": "SUMBERMANJING WETAN",
"data": [
{
"id": 0,
"field": "satu",
"record": "11"
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
}
]
how to change myArray second data record?
this is my code for change update, but there all data is updated, how to change only myArray third data inside myArray[data] ??
//this is my code for update
var update_array = 2;
var update_inside_array = 0;
var valnya = '12';
var arr_data_edit = myArray[update_array].data;
if(arr_data_edit[update_inside_array].id == update_inside_array){
arr_data_edit[idfiledx].record = valnya;
}
console.log(myArray);
I've tried various ways, this is the last one I ran out of ideas, please help to solve this
Thank you for the help
Your current code should work if you simply change idfiledx to update_inside_array:
var update_array = 2;
var update_inside_array = 0;
var valnya = '12';
var arr_data_edit = myArray[update_array].data;
if(arr_data_edit[update_inside_array].id == update_inside_array){
arr_data_edit[update_inside_array].record = valnya;
}
console.log(myArray);
In general, I think it would probably be better to find the item to be updated (the one that has `id: 2`) regardless of its position in the array.
Here's a way to doing that using the .find method of arrays:
const
myArray = [
{ "id": 0, "item": "DONOMULYO", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]},
{ "id": 1, "item": "PAGAK", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]},
{ "id": 2, "item": "BANTUR", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]},
{ "id": 3, "item": "SUMBERMANJING WETAN", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]}
],
outerId = 2,
innerId = 0,
newVal = '12',
outerObj = myArray.find(obj => obj.id == outerId),
innerObj = outerObj.data.find(obj => obj.id == innerId);
innerObj.record = newVal;
console.log(myArray);
.as-console-wrapper{min-height: 100%!important; top: 0}
(Btw, it doesn't look like you use or need any jQuery for this.)
You don't need jQuery, you can use either find or filter, here is an example using filter:
var update_array = 2;
var update_inside_array = 0;
var valnya = '12';
var item = myArray[update_array].data.filter(x => x.id == update_inside_array)[0];
if (typeof item !== 'undefined') item.record = valnya;
console.log(myArray);
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 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 ) );
}
In javascript/jquery how do i achieve following
old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
Using jquery iterate over the above and change to following
new_dataset = [
{
"dob":"xyz",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
},{
"dob":"er",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
}]
If someone can give the code to transform the data it would help me to understand the iteration
You could do something like:
function transformDataset(oldDataset) {
var newDataset = [];
var newObj;
for (var i = 0; i < oldDataset.length; i++) {
newObj = transformObj(oldDataset[i]);
newDataset.push(newObj);
}
return newDataset;
}
function transformObj(obj) {
var children = obj.children;
obj.name = obj.name.first + ' ' + obj.name.last;
obj.start_date = obj.start_date.month + ' ' + obj.start_date.day + ' ' + obj.start_date.year;
obj.children = [];
for (var i = 0; i < children.length; i++) {
obj.children.push(children[i].child.id);
}
return obj;
}
var new_dataset = transformDataset(old_dataset);
Note that new_dataset will have an array of child id instead of an object with multiple child_id properties.
You also had a typo in old_dataset.start_date.month (was written moth)(or maybe that was intentional).
use map first to iterate the array data (old_dataset), replace element name & start_date with new value then return the array
const old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
let new_dataset = old_dataset.map((arr) => {
arr.name = `${arr.name.first} ${arr.name.last}`
arr.start_date = `${arr.start_date.moth} ${arr.start_date.day} ${arr.start_date.year}`
return arr
})
console.log(new_dataset)