Issue
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
Solution
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 large TR
with a lot of TD
in it (as your result shows you).
You need to move them into your loop, the loop that itterates through the rows. Update code:
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>";
for (let i in js.rows) {
text += "<tr>";
for (let j in js.rows[i]) {
text += "<td>" + js.rows[i][j] + "</td>";
}
text += "</tr>";
}
text += "</table>";
document.getElementById("demo").innerHTML = text;
<div id="demo"></div>
Answered By - XMehdi01
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.