I am trying to update a JS object with another object which seems trivial, but the value is not updating.
let sampleObj = {
id: 1,
name: 'Kelly'
}
let userData = [{
students: [{
id: 1,
name: 'Sandra'
}]
},
{
students: [{
id: 2,
name: 'Jerome'
}]
}
]
for (let group of userData) {
for (let student of group.students) {
if (student.id === sampleObj.id) {
console.log('updating student object')
student = sampleObj
// student = { ...sampleObj } (another failed attempt)
// userData[group].students[student] = sampleObj (another failed attempt)
}
}
}
console.log('userData', userData)
It seems like, student is just some floating thing, unassociated to userData at the point where I'm trying to update its value. However, I can't figure out how to make the update or what I'm missing.
EDIT: The expected output is to replace the student object with sampleObj once its found.
sampleObj?studentobject withsampleObjonce its foundstudentonly lives inside the inner for loop, so UserData is not affected from the assignment.group.students.Array.prototype.forEach()that way you have access to the array-element, the index and the array itself.