I have my JSON Data in the below format
{
"RegX": {
"LayerA": {
"name": "abcd123",
"url": "htt:cd1234"
},
"LayerB": {
"name": "xyz234",
"url": "ht:bcd12"
}
},
"RegY": {
"Layer1": {
"name": "xyz123",
"url": "ht/abc1234"
},
"Layer2": {
"name": "xy234",
"url": "http://abc12"
}
}
}
I want to display this in a datatable in below format .
TABLE NAME - REGX
NAME URL
LAYERA abcd123 httd1234
LAYERB xyz234 http:cd12
TABLE NAME - REGY
NAME URL
LAYER1 xyz123 http:d1234
LAYER2 xyz234 h/abcd12
Is there a way that i can display single JSON file in two different tables and display proper Row names and Column names also from JSON table ? I am planning to use datatables but not able to find proper implementation to use
var myData = {
"RegX": {
"LayerA": {
"name": "abcd123",
"url": "htt:cd1234"
},
"LayerB": {
"name": "xyz234",
"url": "ht:bcd12"
}
},
"RegY": {
"Layer1": {
"name": "xyz123",
"url": "ht/abc1234"
},
"Layer2": {
"name": "xy234",
"url": "http://abc12"
}
}
};
var tables = Object.keys(myData);
for(var i=0; i<tables.length; i++){
var rows = Object.keys(myData[tables[i]]);
var tbl = document.createElement('table');
document.getElementsByTagName('body')[0].appendChild(tbl);
var thead = tbl.appendChild(document.createElement('thead'));
thead.innerHTML = ("<tr><td>name</td><td>url</td></tr>");
var tbdy = document.createElement('tbody');
tbl.appendChild(tbdy);
for(var j=0; j<rows.length; j++){
var cols = Object.keys(myData[tables[i]][rows[j]]);
var innerHTML = '';
var tr = tbdy.insertRow(j);
for(var k=0; k<cols.length; k++){
innerHTML += "<td>"+myData[tables[i]][rows[j]][cols[k]]+"</td>";
}
tr.innerHTML = innerHTML;
}
}
table, tr , td {
border-collapse: collapse;
border: 1px solid grey;
}
table {
margin: 5px;
}
Try to understand the code and add more to fulfill your needs.
Hope you got it, if not ask me.
Related
I'm trying to create a table populated by an external .JSON file through using JavaScript. It is not working. When the .JSON data was placed in the .JS code it worked, but once I used "fetch" to retrieve data externally it stopped working and does not display the details.
HTML
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
JavaScript
fetch('about-us.json')
.then((response) => response.json())
.then((data) => {
data.forEach(CreateTableFromJSON);
})
.catch((error) => {
console.error('Error:', error);
});
function CreateTableFromJSON() {
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[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 < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[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);
}
External .JSON File (about-us.json)
[
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}]
I had a little time on my hands so I rewrote your code which breaks down the separate steps to make headings, rows, and cells using map and join, and then uses a template string to piece it together. Basically you're just building up small parts of the final HTML as various strings that you combine.
const json='[{"Book ID":"1","Book Name":"Computer Architecture","Category":"Computers","Price":"125.60"},{"Book ID":"2","Book Name":"Asp.Net 4 Blue Book","Category":"Programming","Price":"56.00"},{"Book ID":"3","Book Name":"Popular Science","Category":"Science","Price":"210.40"}]';
// Cache the button, and add an event listener to
// it which calls the API (returns data after two seconds)
const button = document.querySelector('button');
button.addEventListener('click', fetchData, false);
// Mock API
function mockApi() {
return new Promise(res => {
setTimeout(() => res(json), 2000);
});
}
// Calls the API, parses the json, then
// calls createTable with the data
function fetchData() {
button.textContent = 'Loading...';
button.disabled = true;
mockApi()
.then(res => JSON.parse(res))
.then(createTable);
}
// `map` over the keys of first object
// in the array, and return a string of HTML
function getColumnHeadings(data) {
return Object.keys(data[0]).map(key => {
return `<td>${key}</td>`;
}).join('');
}
// `map` over each object in the array,
// and return a string of HTML. It calls
// `getCells` on each object
function getRows(data) {
return data.map(obj => {
return `<tr>${getCells(obj)}</tr>`
}).join('');
}
// `map` over the values of an object
// and return a string of HTML
function getCells(obj) {
return Object.values(obj).map(value => {
return `<td>${value}</td>`;
}).join('');
}
function createTable(data) {
// Get the headings, and the rows
const headings = getColumnHeadings(data);
const rows = getRows(data);
// Create an HTML string
const html = `
<table>
<tbody>
<tr class="headings">${headings}</tr>
${rows}
</tbody>
</table>
`
// Add the string to the DOM
document.body.insertAdjacentHTML('beforeend', html);
}
table { border-collapse: collapse; border: 1px solid #565656; margin-top: 1em; width: 100%; }
td { padding: 0.6em 0.3em; border: 1px solid #dfdfdf; }
.headings { font-weight: 700; background-color: #dfdfdf; }
button:hover { cursor: pointer; }
<button>Build table</button>
I want to create an HTML table using json data. The json data will change over time. When convert this json data to an HTML table, the table looks like this with consistent. It means the alignment of values and the width of the table. How can I convert the json data into an HTML table?
[
{
"1": [{
"Time": "01:35 AM",
"Location": "dhaka bangladesh",
"BUS Detail": {
"air_Logo": "logo goes here",
"air_Name": "Airbus"
},
"busNo": "AK119",
"arrTime": "05:40 AM",
"arrival Loc": "barisal"
}]
}
]`// Extract value from table header.
let col = [];
for (let i = 0; i < myBooks.length; i++) {
for (let key in myBooks[i]) {
if (col.indexOf(key) == -1) {
col.push(key);
}
}
}
// Create a table.
const table = document.createElement("table");
// Create table header row using the extracted headers above.
let tr = table.insertRow(-1); // table row.
for (let i = 0; i < col.length; i++) {
let th = document.createElement("th"); // table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
// add json data to the table as rows.
for (let i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
const tabcel = tr.insertCell(-1);
if (typeof myBooks[i][col[j]] === 'object') {
tabcel.setAttribute('rowspan','2');
tabcel.innerHTML = `<table><td>${myBooks[i][col[j]].air_Name}</td> <td> ${myBooks[i][col[j]].air_Logo}</td> </table>`;
} else {
tabcel.innerHTML = myBooks[i][col[j]];
}
}
// for (let j = 0; j < col.length; j++) {
// let tabCell = tr.insertCell(-1);
// tabCell.innerHTML = myBooks[i][col[j]];
// }
}
// Now, add the newly created table with json data, to a container.
const divShowData = document.getElementById('showData');
divShowData.innerHTML = "";
divShowData.appendChild(table);`
Since your object is not flat, you cannot truly render it all to table. You have to make a decision about the nested objects. Below I am simply using json.stringify to show those objects in a table cell. You should of course handle this according to your needs.
const data = [
{
"1": [
{
Time: "01:35 AM",
Location: "dhaka bangladesh",
"BUS Detail": {
air_Logo: "logo goes here",
air_Name: "Airbus"
},
busNo: "AK119",
arrTime: "05:40 AM",
"arrival Loc": "barisal"
}
]
}
];
const base = data[0]["1"];
const table = document.createElement("table");
const thead = table.createTHead();
const tbody = document.createElement("tbody");
table.append(tbody)
const headRow = thead.insertRow();
const headers = Object.keys(base[0]).forEach((head) => {
let cell = headRow.insertCell();
cell.textContent = head;
});
base.forEach((obj) => {
const row = tbody.insertRow();
const vals = Object.values(obj);
vals.forEach((v) => {
const cell = row.insertCell();
if (typeof(v) !== 'string') {
return cell.textContent = JSON.stringify(v);
}
cell.textContent = v
});
});
document.body.append(table)
i would like to display only details of Linda using JSON. However, I am clueless on how to do it. Need some advice, thanks!
The output should show the updated table with only "Linda" instead of my current output.
Actual question:
Using JSON, modify the mobile of Linda to 88885555, and display only the details of Linda.
My employees object is supposed to be from .json file but i couldnt find the format to insert into this post. Hence, i combined it into my .js file.
var employees = [
{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").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(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable()">
<table id="employeeTable" border="1"></table>
</body>
You can create a function that accepts an "employee name", .not() and .is() to match any <td> elements within the <tr> where .textContent is equal to the argument passed to the function, chain .hide() to set the display of the matched elements to "none".
To display all <tr> elements you can use $("#employeeTable tr").show().
Substituted using jQuery(function(){}) for onload attribute event handler at <body> element.
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").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(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<!DOCTYPE html>
<html>
<head>
<title>Task 1</title>
<!-- using of jquery, calling external js file -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table id="employeeTable" border="1">
</table>
<script>
$(function() {
buildHtmlTable();
function hideRow(employeeName) {
return $("#employeeTable tr").not(function(index, element) {
return $(element.cells).is(function(i, el) {
return el.textContent === employeeName
});
}).hide();
}
hideRow("Linda");
});
</script>
</body>
</html>
If I understood your question correctly you could do something like I did below. I used setTimeout so you can see the transition from your original output to the updated output:
function buildTable(arr) {
let html = "<table border='1' style='width: 100%'>";
for (let i = 0; i < arr.length; i++) {
html += `<tr>
<td>${arr[i].Name || ''}</td>
<td>${arr[i].Mobile || ''}</td>
<td>${arr[i].Email || ''}</td>
</tr>`;
}
html += "</table>";
return html;
}
function init() {
const LINDA_IDX = 1;
container.innerHTML = buildTable(employees);
setTimeout(function() { //
//Update Linda's phone number
employees[LINDA_IDX].Mobile = 88885555;
//Show just Linda in the table
container.innerHTML = buildTable([employees[LINDA_IDX]])
}, 2000);
}
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
}, {
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
}, {
"Name": "Patrick",
"Email": "patrick#json.com"
}, {
"Name": "Isabella",
"Mobile": 99552222
}];
var container = document.querySelector('#container');
init();
After 2 seconds setTimeout will execute showing Linda's updated info:<br />
<div id="container"></div>
I have something like this, but bigger.
[{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}]
I am trying for hours to transform this array into a table.
My goal is to put in the first column of the table the last zones (in our case zone2 and zone3) in voting_section (for example, the first column will have 2 lines: Delaware and Los Angeles.
In the header of the table I want to put all the other properties(votes, invalid_votes, valid_votes).
The intersection will be completed with the values:
So it has to be something like this:
Here I have my code so far, but I don't think I'm going in a good direction:
function createTableKeyValue2(arrObjects, parentDiv) {
var elTable = document.createElement("table");
elTable.className = "table table-striped table-bordered";
var elTableBody = document.createElement("tbody");
for (var i = 0; i < arrObjects.length; i++) {
var elTableRow = document.createElement("tr");
var elTableDataKey = document.createElement("td");
elTableDataKey.innerHTML = arrObjects[i];
var elTableDataValue = document.createElement("td");
elTableDataValue.innerHTML = arrObjects[i];
//elTableDataValue.id = arrObjects[i].key.split(' ').join('_');
elTableRow.appendChild(elTableDataKey);
elTableRow.appendChild(elTableDataValue);
elTableBody.appendChild(elTableRow);
}
elTable.appendChild(elTableBody);
parentDiv.append(elTable);
}
var votingSection = function(zone) {
var voting_section = [];
var level = zone[0].voting_section.level;
for (var i = 0; i < zone.length; i++) {
voting_section.push(zone[i].voting_section['zone' + level]);
}
return voting_section;
};
createTableKeyValue(votingSection(zone2), resultsTableDiv);
resultTableDiv is a node in the DOM.
I've interpreted your question as though you want to extract 1 zone from voting_section, that zone should have the highest number appended to it.
var data = [{
"votes": 200,
"invalid_votes": 140,
"valid_votes": 60,
"voting_section": {
"level": 1,
"zone1": "US",
"zone2": "Delaware"
}
},
{
"votes": 300,
"invalid_votes": 40,
"valid_votes": 260,
"voting_section": {
"level": 1,
"zone1": "US",
"zone2": "California",
"zone3": "Los Angeles"
}
}
],
html = "";
function getLastZone(voting_section) {
var highestZone = {
zoneNumber: null,
zoneText: null
};
for (var zone in voting_section) {
var checkZone = /zone(\d)/g.exec(zone);
if (checkZone) {
if (parseInt(checkZone[1]) > highestZone.zoneNumber) {
highestZone = {
zoneNumber: [checkZone[1]],
zoneText: voting_section[zone]
};
}
}
}
return highestZone.zoneText;
}
data.forEach(function(e, i) {
html += "<tr>" + "<td>" + getLastZone(e.voting_section) + "</td>" +
"<td>" + e.votes + "</td>" +
"<td>" + e.valid_votes + "</td>" +
"<td>" + e.invalid_votes + "</td>" + "</tr>";
})
document.getElementById("putHere").innerHTML = html;
table {
border-collapse: collapse;
border-left: 1px solid #bbbbbb;
border-top: 1px solid #bbbbbb;
}
th, td {
border-right: 1px solid #bbbbbb;
border-bottom: 1px solid #bbbbbb;
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<table>
<thead>
<th>Zone</th>
<th>Votes</th>
<th>Valid Votes</th>
<th>Invalid Votes</th>
</thead>
<tbody id="putHere"></tbody>
</table>
</body>
</html>
You could create one main function to build the table, from which you could call a row-building function (while iterating over the data rows). I've added an example to my post here.
var data = [{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}];
var buildTable = function(data, container){
/* Builds one data row into a <tr> element string */
var buildRow = function(rowData){
return `<tr><td>${rowData.voting_section.zone2}</td><td>${rowData.votes}</td><td>${rowData.valid_votes}</td><td>${rowData.invalid_votes}</td></tr>`;
}
/* Reduces the array of row data into one string */
var rows = data.reduce(function(rows, row){
return rows+buildRow(row);
}, '');
/* Creates the full table and includes the rows string */
container.innerHTML = `<table><thead><tr><td></td><td>Votes</td><td>Valid Votes</td><td>Invalid Votes</td></tr></thead><tbody>${rows}</tbody>`;
}
var resultsTableDiv = document.getElementById('results')
buildTable(data, resultsTableDiv);
<div id="results"></div>
You can create a table from it using the javascript DOM objects,
myArray = [{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}]
table = document.getElementById("myTable")
//In case is is called multiple times this forces the table to be empty
while(table.rows[0] !== undefined) {
table.deleteRow(0)
}
//Creates the empty cell in the top left
row = table.insertRow(0)
row.insertCell(0)
pos = 0
//Creates the column labels
for(var name in myArray[0]) {
if (name !== "voting_section") {
pos += 1
cell = row.insertCell(pos)
cell.innerHTML = name
}
}
//creates the row labels, by changing how the last item is selected or what it contains you can produce a different label
for (var i = 0; i < myArray.length; i++) {
row = table.insertRow(i+1)
lastItem = myArray[i].voting_section[Object.keys(myArray[i].voting_section)[Object.keys(myArray[i].voting_section).length - 1]]
row.insertCell(0).innerHTML = lastItem
}
//creates the values
pos = 0
for(var name in myArray[0]) {
if (name !== "voting_section"){
pos += 1
for (var i = 0; i < myArray.length; i++) {
row = table.rows[i+1]
cell = row.insertCell(pos)
cell.innerHTML = myArray[i][name]
}
}
}
I have a json file in my website project, like this:
[
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
]
Here it is the sample data, It has 4 columns but i don't know that my json data which i will get, will have how many number of columns. I am trying to create a dynamic html table from this json data. This is the code i have write now:
<script>
$(document).ready(function () {
var jsonitems = [];
$.getJSON("json.json", function (data) {
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
above code is working, I am facing problem when i try to insert data rows, below is the code for that which is not working:
//Add the data rows.
//for (var i = 1; i < data.length; i++) {
// row = table.insertRow(-1);
// for (var j = 0; j < totalColumns; j++) {
// var cell = row.insertCell(-1);
// cell.innerHTML = customers[i][j];
// }
//}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
});
});
</script>
Please help me with that.
Thanks
The way you are accessing the cell data is wrong. For example, to access id of first object, you've to do data[0]["id"], instead your code tries to do data[0][0]. Working example of your code:
var data = [{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
// Add the data rows.
for (var i = 0; i < data.length; i++) {
row = table.insertRow(-1);
columnNames.forEach(function(columnName) {
var cell = row.insertCell(-1);
cell.innerHTML = data[i][columnName];
});
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
<div id="dvTable"></div>
Based on what I can interpret, you can just do this. Access each object inside the array, then use the keys to map your values.
But what you've written as your example code and your provided data seems different.
let data = [
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var table = document.getElementById("table");
for (let item of data) {
row = table.insertRow(-1);
for (let key in item) {
var cell = row.insertCell(-1);
cell.innerHTML = item[key];
}
}
<table id="table">
</table>