JSON array
let arrItems = [
{ID: '001', 'Bird Name': "Black Vulture", Type : 'Hawk'},
{ID: '002', 'Bird Name': "Rock Pigeon", Type: 'Dove' },
{ID: '003', 'Bird Name': "Bell's Sparrow", Type: 'Sparrow' }
];It has just three nodes, ID, Bird Name and Type.
The Script
<body>
<div id='myTable'></div>
</body>
<script>
let createTableFromArray = () => {
// the array.
let arrItems = [
{ID: '001', 'Bird Name': "Black Vulture", Type : 'Hawk'},
{ID: '002', 'Bird Name': "Rock Pigeon", Type: 'Dove' },
{ID: '003', 'Bird Name': "Bell's Sparrow", Type: 'Sparrow' }
];
// Get values for the table header.
let col = [];
for (let i = 0; i < arrItems.length; i++) {
for (let key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// Create a Table.
let table = document.createElement("table");
// Create table header row.
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);
th.setAttribute ('style',
'border: solid 1px #DDD;' +
'border-collapse: collapse; font-weight:bold;' +
'padding: 2px 3px; text-align: center;');
}
// Add JSON to the table as rows.
for (let z = 0; z < arrItems.length; z++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
let tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[z][col[j]];
tabCell.setAttribute ('style',
'border: solid 1px #DDD;' +
'border-collapse: collapse; ' +
'padding: 2px 3px; text-align: center;');
}
}
// Show the table.
let container = document.getElementById('myTable');
container.innerHTML = '';
container.appendChild(table);
}
createTableFromArray();
</script>That’s it. Its simple and you don’t need any framework to do this. JavaScript is enough. However, if you still want to use jQuery (for some reason) to convert an array into a Table, then you must see this post.
