Issue
I am trying to create a set of dynamic HTML tables using JS.
I am taking in data from an array of objects, in the following format:
const formPages = [
{
"name": "page1",
"response": [
{
"question": "Question 1",
"response": "Hello!"
},
{
"question": "Question 2",
"response": "Hello again!"
}
]
},
{
"name": "page2",
"response": [
{
"question": "Question 3",
"response": "Bye!"
},
{
"question": "Question 4",
"response": "Bye again!"
}
]
}
]
I need to output a table for each page in the following format:
Page 1
Question | Response |
---|---|
Question 1 | Hello! |
Question 2 | Hello Again! |
Page 2
Question | Response |
---|---|
Question 3 | Bye! |
Question 4 | Bye Again! |
I know we need to loop over the array of objects, dynamically rendering the HTML to output those two tables.
Don't have much experience with table HTML, so some help here would be great!
Thanks in advance!
Solution
You could do something like below, see comments for explanation
const formPages = [
{
"name": "page1",
"response": [
{
"question": "Question 1",
"response": "Hello!"
},
{
"question": "Question 2",
"response": "Hello again!"
}
]
},
{
"name": "page2",
"response": [
{
"question": "Question 3",
"response": "Bye!"
},
{
"question": "Question 4",
"response": "Bye again!"
}
]
}
]
//refer to the placeholder div:
const placeholderDiv = document.getElementById('table-placeholder');
//loop over all pages:
formPages.forEach(page =>{
//create an element that contains the page
let h2 = document.createElement('h2');
h2.innerText = page.name;
//add the element to the div
placeholderDiv.appendChild(h2);
//create a table within the foreach loop so you get a seperate table for every page
let table = document.createElement('table');
//here the headers are set static, you could chose to also make this dynamic and refer to the object.keys for the response for example
table.innerHTML ='<thead><tr><th>Question</th><th>Response</th></thead>';
let tbody = document.createElement('tbody');
//append the body to the table
table.appendChild(tbody)
//loop over the responses
page.response.forEach(question =>{
//create a row
let trow = document.createElement('tr')
//create a cell within the row
let questionCell = document.createElement('td')
//set the innerText of the cell with the value from question
questionCell.innerText = question.question;
//create another cell within the row
let responseCell = document.createElement('td')
//set the innerText of the cell with the value from the response
responseCell.innerText = question.response;
//append both cells to the row
trow.appendChild(questionCell);
trow.appendChild(responseCell);
//append the row to the table body
tbody.appendChild(trow)
})
//append the entire table to the div
placeholderDiv.appendChild(table)
})
<div id='table-placeholder'> </div>
Answered By - kernell
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.