Here is my student score json file :
(the idea is creating a function to change specific student 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' },
]
}
]
}
]
How to do that?
For example
from class A change second student physic score to from 12 to 20
I’ve tried foreach and map but I didn’t get the result that I want
2
Answers
To write a function that updates the score of a specific Student for a specific subject, we should pass the five parameters to the function:
For convenience, we will return the changed data.
Below an implementation, you could write it shorter but I preferred readability. Keep in mind I only follow the ‘happy path’ and you should best add some validation if (for example) a student is not found.
Here’s a solution to change the score for a specific student in a specific class. I’ll show you how to do it with a pure JavaScript function first, and then I’ll use Lodash. You can create a copy of the classesData array, update the score for the specific student, and return the modified copy without affecting the original data.
You can use map to create a new copy of the array and update the student’s score on this new copy without affecting the original data;
Lodash provides utility functions like cloneDeep to easily make deep copies of objects Here’s the Lodash approach to achieve the same goal:
Explanation:
In both examples, we first create a deep copy of the original classesData to prevent modifying it directly.
Find the class: Using find to search the classesData array by class name.
Find the student: Inside the class, use find again to locate the student.
Update the score: Search the student’s results array to locate the correct subject and update the score.
Pure JavaScript functions solution
we use map and the spread operator
(...)
to create new copies of the objects and update the score.Lodash solution
_.cloneDeep
creates the deep copy, and_.find
is used to locate the class, student, and result, while_.set
updates the score.Both solutions ensure the original data remains unaltered, and you get a modified copy of classesData.