这是我的学生成绩json文件:
(这个想法是创建一个函数来改变特定的学生分数)
const classesData = [
{
name: 'A',
books: [
{ name: 'math' },
{ name: 'chemistry' },
{ name: 'physic' }
],
students: [
{
name: 'first student',
results: [
{ name: 'math', score: '20' },
{ name: 'chemistry', score: '14' },
{ name: 'physic', score: '16' },
]
},
{
name: 'second student',
results: [
{ name: 'math', score: '15' },
{ name: 'chemistry', score: '10' },
{ name: 'physic', score: '12' },
]
}
]
},
{
name: 'B',
books: [
{ name: 'math' },
{ name: 'chemistry' },
{ name: 'physic' }
],
students: [
{
name: 'first student',
results: [
{ name: 'math', score: '20' },
{ name: 'chemistry', score: '14' },
{ name: 'physic', score: '16' },
]
},
{
name: 'second student',
results: [
{ name: 'math', score: '15' },
{ name: 'chemistry', score: '10' },
{ name: 'physic', score: '12' },
]
}
]
}
]
要编写一个更新特定学生特定科目分数的函数,我们应该将四个参数传递给该函数:
function patchScore(data, student, subject, score) {}
为了方便,我们将返回更改后的数据。
在实现下面,你可以写得更短,但我更喜欢可读性。请记住,我只遵循“快乐之路”,如果(例如)找不到学生,您最好添加一些验证。
const classesData = [
{
name: 'A',
books: [
{ name: 'math' },
{ name: 'chemistry' },
{ name: 'physic' }
],
students: [
{
name: 'first student',
results: [
{ name: 'math', score: '20' },
{ name: 'chemistry', score: '14' },
{ name: 'physic', score: '16' },
]
},
{
name: 'second student',
results: [
{ name: 'math', score: '15' },
{ name: 'chemistry', score: '10' },
{ name: 'physic', score: '12' },
]
}
]
},
{
name: 'B',
books: [
{ name: 'math' },
{ name: 'chemistry' },
{ name: 'physic' }
],
students: [
{
name: 'first student',
results: [
{ name: 'math', score: '20' },
{ name: 'chemistry', score: '14' },
{ name: 'physic', score: '16' },
]
},
{
name: 'second student',
results: [
{ name: 'math', score: '15' },
{ name: 'chemistry', score: '10' },
{ name: 'physic', score: '12' },
]
}
]
}
]
let patchedData = patchScore(classesData, 'first student', 'math', 1);
console.log(patchedData)
function patchScore(data, student, subject, score) {
// Find student
let matchedStudent = data[0].students.find((s) => s.name === student)
// Find subject
let matchedSubject = matchedStudent.results.find((s) => s.name === subject)
// Update score
matchedSubject.score = score
return data;
}