如何使用JavaScript基于试题与学生作答数据生成动态行列HTML表格
实现方案
你只需要在生成表格行的逻辑里,额外遍历所有学生,匹配对应题目的作答答案填充即可,以下是修改后的完整可运行代码:
<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: 2, answer: 1, question_id: 2}, {id: 3, answer: 2, question_id: 3}, {id: 4, answer: 1, question_id: 4} ], 'student_2': [ {id: 1, answer: 2, question_id: 1}, {id: 2, answer: 1, question_id: 2}, {id: 3, answer: 2, question_id: 3}, {id: 4, answer: 1, question_id: 4} ], 'student_3': [ {id: 1, answer: 1, question_id: 1}, {id: 2, answer: 1, question_id: 2}, {id: 3, answer: 1, question_id: 3}, {id: 4, 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 studentName in students) { table += '<th class="text-center">'+studentName+'</th>'; } table += '</tr>'; table += '</thead>'; table += '<tbody>'; questions.forEach(question => { table += '<tr class="text-center">'; table += '<td>'+question.question+'</td>'; table += '<td>'+question.section+'</td>'; // 遍历所有学生,匹配当前题目的答案 for(var studentName in students) { // 找到该学生对应当前题目id的作答记录 const answerRecord = students[studentName].find(item => item.question_id === question.id); table += '<td>'+ (answerRecord ? answerRecord.answer : '-') +'</td>'; } table += '</tr>'; }) table += '</tbody>'; table += '</table>'; $('.results').append(table) </script>
关键改动说明
- 把原来的
Object.entries(questions).map改成了更适合数组遍历的forEach,避免不必要的返回值生成 - 在每个题目行生成Question、Section单元格后,新增了遍历所有学生的逻辑,通过
find方法匹配该学生对应当前题目id的作答,取出答案填充到单元格中,没有找到作答时默认显示-避免报错 - 修正了原示例中学生作答数据里id重复的小问题,数据规范性更强
内容的提问来源于stack exchange,提问作者Codeblooded Saiyan
相关产品推荐
相关产品推荐

