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.
Use forEach(el, index) instead so you have the index available to do the update:
let sampleObj = {
id: 1,
name: 'Kelly'
}
let userData = [{
students: [{
id: 1,
name: 'Sandra'
}]
},
{
students: [{
id: 2,
name: 'Jerome'
}]
}
]
userData.forEach((group, m) => {
group.students.forEach((student, n) => {
if (student.id === sampleObj.id) {
console.log('updating student object')
userData[m].students[n] = sampleObj
}
})
})
console.log('userData', userData)
Array item replacement does not work that way. Instead you can replace the properties of student object like this
for (let group of userData) {
for (let student of group.students) {
if (student.id === sampleObj.id) {
console.log('updating student object')
student = Object.assign(student, sampleObj);
}
}
}
It'll assign all the properties of samplObj to student object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With