Introduction
This article will provide a step-by-step guide on how to convert a Javascript JSON array of objects to an HTML table. We will discuss the different methods of converting the array into a table, as well as the advantages and disadvantages of each approach. We will also provide code examples to help you get started. By the end of this article, you should have a better understanding of how to convert a Javascript JSON array of objects to an HTML table.
Solution
// Create a function to convert the JSON array of objects to an HTML table
function jsonToTable(json) {
// Create an empty string to store the HTML table
let table = ”;
// Iterate through the JSON array
for (let i = 0; i < json.length; i++) {
// Create a row for each object in the array
table += '
// Iterate through the object’s properties
for (let key in json[i]) {
// Create a cell for each property
table += ‘
‘;
}
// Close the row
table += ‘
‘;
}
// Return the HTML table
return ‘
‘;
}
The order is wrong. out is an object of arrays (not an array of objects). Here I fixed the order of access with the assumption, that all properties contain an array with the same length:
function fetch() {
return Promise.resolve({
json() {
return Promise.resolve({
"name": [
"John",
"Marie",
"Clara"
],
"surname": [
"Doe",
"Jane",
"Smith"
],
"phone": [
"1233215555",
"1233215555",
"1233215555"
],
"birthdate": [
"1980-12-14",
"1990-02-13",
"1995-03-10"
]
})
}
});
}
var url = "some-url";
fetch(url)
.then(res => res.json())
.then((out) => {
for (let i = 0; i < out.name.length; i++) {
console.log(out.name[i] + " " + out.surname[i] + " " + out.phone[i] + " " + out.birthdate[i])
}
})
4
solved Javascript JSON array of objects to HTML table