I'm trying to use javascript to convert this JSON data into HTML table.
This is my code so far; however, I am confused about how to process the 'contacts'
part and put them into a cell like this: first_name + last_name + position of the CEO and CTO
.
I was thinking of using company_info[i]["contacts"].forEach(function(e){}
to extract the contacts data but I am not sure how to put it together in the cell.
Any help appreciated!
My code:
function CreateTableFromJSON() {
var company_info = [{
"id": 1,
"company_name": "ACompany",
"established": 1999,
"industry": "Tech",
"contacts": [{
"first_name": "AAFirst",
"last_name": "AALast",
"position": "CEO"
},
{
"first_name": "ABFirst",
"last_name": "ABLast",
"position": "CTO"
}
]
},
{
"id": 2,
"company_name": "BCompany",
"established": 1998,
"industry": "Med",
"contacts": [{
"first_name": "BAFirst",
"last_name": "BALast",
"position": "CEO"
},
{
"first_name": "BBFirst",
"last_name": "BBLast",
"position": "CTO"
}
]
},
{
"id": 3,
"company_name": "CCompany",
"established": 1997,
"industry": "Ivest",
"contacts": [{
"first_name": "CAFirst",
"last_name": "CALast",
"position": "CEO"
},
{
"first_name": "CBFirst",
"last_name": "CBLast",
"position": "CTO"
}
]
},
{
"id": 4,
"company_name": "DCompany",
"established": 1996,
"industry": "Tech",
"contacts": [{
"first_name": "DAFirst",
"last_name": "DALast",
"position": "CEO"
},
{
"first_name": "DBFirst",
"last_name": "DBLast",
"position": "CTO"
}
]
},
{
"id": 5,
"company_name": "ECompany",
"established": 1995,
"industry": "Med",
"contacts": [{
"first_name": "EAFirst",
"last_name": "EALast",
"position": "CEO"
},
{
"first_name": "EBFirst",
"last_name": "EBLast",
"position": "CTO"
}
]
}
]
// EXTRACT VALUE FOR HTML HEADER.
// ('ID', 'Company Name', 'Established','Industry', 'Contacts')
var col = [];
for (var i = 0; i < company_info.length; i++) {
for (var key in company_info[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
//Create a table
var table = document.createElement("table");
//Create table rows
var tr = table.insertRow(-1);
//Create table headers
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 table as rows
for (var i = 0; i < company_info.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = company_info[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
<html>
<head>
<title>Convert JSON Data to HTML Table</title>
<style>
table, th, td
{
margin:10px 0;
border:solid 1px #333;
padding:2px 4px;
font:15px Verdana;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<div id="showData"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>