【发布时间】:2021-12-05 04:08:35
【问题描述】:
我有这些数据集
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}
]
}
如何使用以上数据创建表格?结果应该是:
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 |
我有这个初始的 javascript 代码,但我很困惑如何填写学生的数据
<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>
【问题讨论】:
-
对下面我的回答有任何疑问吗?
标签: javascript html-table