我正在尝试使用
javascript将此
JSON数据转换为HTML表格.
到目前为止这是我的代码;但是,我对如何处理“联系人”部分并将它们放入这样的单元格感到困惑:first_name last_name首席执行官和首席技术官的职位.
我正在考虑使用company_info [i] [“contacts”].forEach(function(e){}来提取联系人数据,但我不知道如何将它们放在单元格中.
任何帮助赞赏!
我的代码:
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);
}
Convert JSON Data to HTML Tabletable, th, td
{
margin:10px 0;
border:solid 1px #333;
padding:2px 4px;
font:15px Verdana;
}
th {
font-weight:bold;
}