JavaScript中如何向数组推送包含动态学年字段的学生成绩数据?
实现代码
首先对齐预设数据结构(如果你的实际结构和示例不同,对应修改匹配逻辑即可):
// 已初始化的学生数组示例 const students = [ { id: 101, name: '张明', ObtainedMarks: {} }, { id: 102, name: '李华', ObtainedMarks: {} } ] // 前端参数解析得到的newObj示例:键对应学生数组索引,值为按学年顺序排列的物理成绩 const newObj = { 0: [79, 85, 93], // 第1个学生的1/2/3年级成绩 1: [88, 90, 82] // 第2个学生的1/2/3年级成绩 }
核心逻辑
不需要单独做“同步双循环”的特殊处理,两层for循环按索引一一匹配即可完成需求:
// 第一层遍历所有学生 for (let stuIndex = 0; stuIndex < students.length; stuIndex++) { // 拿到当前学生对应的学年成绩列表 const scoreList = newObj[stuIndex] // 第二层遍历对应学生的所有学年成绩 for (let yearIndex = 0; yearIndex < scoreList.length; yearIndex++) { // 生成动态学年键名:1st-Year、2nd-Year... const suffix = ['st', 'nd', 'rd', 'th'][Math.min(yearIndex, 3)] const yearKey = `${yearIndex + 1}${suffix}-Year` // 写入成绩到对应字段 students[stuIndex].ObtainedMarks[yearKey] = { physics: scoreList[yearIndex] } } }
最终输出结构示例
[ { id: 101, name: '张明', ObtainedMarks: { "1st-Year": { physics: 79 }, "2nd-Year": { physics: 85 }, "3rd-Year": { physics: 93 } } }, { id: 102, name: '李华', ObtainedMarks: { "1st-Year": { physics: 88 }, "2nd-Year": { physics: 90 }, "3rd-Year": { physics: 82 } } } ]
注意事项
- 如果你的newObj是用学生ID作为键而非数组索引,把第一层的匹配逻辑改成按ID筛选对应学生即可
- 可以提前加长度校验避免数据不匹配报错:
if (students.length !== Object.keys(newObj).length) { throw new Error('学生数量和成绩数据数量不匹配') }
内容的提问来源于stack exchange,提问作者sophia
相关产品推荐
相关产品推荐

