On my hands, I hold a JavaScript array structured like this:
const Rooms = [{
name:"Science",
students:[
{user:"Tom",emotion:"Happy"},
{user:"Marry",emotion:"Angry"},
{user:"Adam",emotion:"Happy"}
]
},{
name:"Maths",
students:[
{user:"Stewie",emotion:"Angry"},
{user:"Cleavland",emotion:"Angry"},
{user:"Meg",emotion:"Happy"},
{user:"Peter",emotion:"Angry"},
{user:"Chris",emotion:"Happy"}
]
},{
name:"History",
students:[
{user:"Monica",emotion:"Angry"},
{user:"Chandler",emotion:"Happy"},
{user:"Joe",emotion:"Happy"},
{user:"Ross",emotion:"Angry"}
]
}];
I am seeking a way to identify a room by its name and modify or insert a student as needed. For instance, I should be able to locate the room named "Maths" and update a student within it. If the student is already listed, only their emotion needs to change.
The following code snippet was my initial attempt, but it failed to replace the existing student:
Rooms.forEach((e)=>{
if(e.name === "Science"){
e.students.push({user:"Tom",emotion:"Surprised"});
}
});
How can I effectively search for a specific JSON entry and either alter an existing student's details or introduce a new student (in case they are not present)?