I a little new to JS and was struggling to display JSON data in a tabular format. The JSON is below
var js = {
"columns": [{
"title": "t1"
},
{
"title": "t2"
},
{
"title": "t3"
},
{
"title": "t4"
},
{
"title": "t5"
}
],
"rows": [
[
"t1row1",
"t2row1",
"t3row1",
"t4row1",
"t5row1"
],
[
"t1row2",
"t2row2",
"t3row2",
"t4row2",
"t5row2"
],
[
"t1row3",
"t2row3",
"t3row3",
"t4row3",
"t5row3"
]
]
};
let text = "<table border='1'>"
text += "<tr>";
for (let x in js.columns) {
text += "<th>" + js.columns[x].title + "</th>";
}
text += "</tr>";
text += "<tr>";
for (let y in js.columns) {
for (var v in js.rows) {
text += "<td>" + js.rows[v] + "</td>";
}
}
text += "</tr>";
text += "</table>"
document.getElementById("demo").innerHTML = text;
<div id="demo"></div>
I have used these loops to get the data in tabular format but I am unable to send the "rows" data into 3 separate rows under the titles. By the current code I am able to put the 5 column name correctly but we have a single row with [t1row1,t2row1,t3row1,t4row1,t5row1] , [t1row2,t2row2,t3row2,t4row2,t5row2] …etc with data inserted instead of 3 rows. Any help would be appreciated
3
Answers
To achieve your result, you need to iterate over the rows of data and add them to the table while preserving the structure. You have the open/close
TR
outside of your loop. That means you’re making one largeTR
with a lot ofTD
in it (as your result shows you).You need to move them into your loop, the loop that itterates through the rows. Update code:
You just need to fix your loop within the row values, not using loop with columns values.
also you need to set tags inside loop to create row for each object
Here you can find how to get it fixed
table element have specific method you should use : https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement