I have a JSON array like the following:
[
{
"_id": "5c3296f4c7728833bf7cf334",
"title": "Update styling",
"content": "Don't forget to update the styling on the website",
"category": "Cat2",
"createdAt": "2019-01-07T00:01:56.375Z",
"updatedAt": "2019-01-07T00:01:56.375Z",
"__v": 0
}
]
I want to populate a html table with the Title, Content and Category fields. Currently, I am using the following code to populate the table, but it puts every field in the table, not the ones I want.
const data = [{ "_id": "5c3296f4c7728833bf7cf334", "title": "Update styling", "content": "Don't forget to update the styling on the website", "category": "Cat2", "createdAt": "2019-01-07T00:01:56.375Z", "updatedAt": "2019-01-07T00:01:56.375Z", "__v": 0 }]
const axios = { get: (s) => Promise.resolve({ data }) };
window.addEventListener('load', function() {
axios.get('http://localhost:2672/categories').then(function (myCategories) {
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < myCategories.data.length; i++) {
for (var key in myCategories.data[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 < myCategories.data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myCategories.data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showCategories");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
<div id="showCategories"></div>
Any ideas how I would accomplish this?