I have these sets of data
var questions = [
{ id: 1, 'question': 1, 'section': 1 },
{ id: 2, 'question': 1, 'section': 2 },
{ id: 3, 'question': 2, 'section': 1 },
{ id: 4, 'question': 2, 'section': 2 }
]
var students = {
'student_1': [
{id: 1, answer: 1, question_id: 1},
{id: 1, answer: 1, question_id: 2},
{id: 1, answer: 2, question_id: 3},
{id: 1, answer: 1, question_id: 4}
],
'student_2': [
{id: 1, answer: 2, question_id: 1},
{id: 1, answer: 1, question_id: 2},
{id: 1, answer: 2, question_id: 3},
{id: 1, answer: 1, question_id: 4}
],
'student_3': [
{id: 1, answer: 1, question_id: 1},
{id: 1, answer: 1, question_id: 2},
{id: 1, answer: 1, question_id: 3},
{id: 1, answer: 1, question_id: 4}
]
}
How can I create a table using the data above? the result should be:
Question | Section | student_1 | student_2 | student_3 |
__________________________________________________________________________
1 | 1 | 1 | 2 | 1 |
__________________________________________________________________________
1 | 2 | 1 | 1 | 1 |
__________________________________________________________________________
2 | 1 | 2 | 2 | 1 |
__________________________________________________________________________
2 | 2 | 1 | 1 | 1 |
I have this initial javascript code, but I'm confused how to fill the data from students
<div class="results"></div>
<script>
var questions = [
{ id: 1, 'question': 1, 'section': 1 },
{ id: 2, 'question': 1, 'section': 2 },
{ id: 3, 'question': 2, 'section': 1 },
{ id: 4, 'question': 2, 'section': 2 }
]
var students = {
'student_1': [
{id: 1, answer: 1, question_id: 1},
{id: 1, answer: 1, question_id: 2},
{id: 1, answer: 2, question_id: 3},
{id: 1, answer: 1, question_id: 4}
],
'student_2': [
{id: 1, answer: 2, question_id: 1},
{id: 1, answer: 1, question_id: 2},
{id: 1, answer: 2, question_id: 3},
{id: 1, answer: 1, question_id: 4}
],
'student_3': [
{id: 1, answer: 1, question_id: 1},
{id: 1, answer: 1, question_id: 2},
{id: 1, answer: 1, question_id: 3},
{id: 1, answer: 1, question_id: 4}
]
}
var table = '<table class="table table-bordered">';
table += '<thead>';
table += '<tr style="background-color: #e5e5e5;">';
table += '<th>Question</th>';
table += '<th>Section</th>';
for(var idx in students) {
table += '<th class="text-center">'+idx+'</th>';
}
table += '</tr>';
table += '</thead>';
table += '<tbody>';
Object.entries(questions).map(([key, question]) => {
table += '<tr class="text-center">';
table += '<td>'+question.question+'</td>';
table += '<td>'+question.section+'</td>';
table += '</tr>';
})
table += '</tbody>';
table += '</table>';
$('.results').append(table)
</script>
Here's the fiddle: https://jsfiddle.net/pLeqd8no/