Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Javascript object property inside for loop

Tags:

javascript

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.

like image 951
bruh Avatar asked Jun 07 '26 02:06

bruh


2 Answers

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)
like image 194
connexo Avatar answered Jun 08 '26 16:06

connexo


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.

like image 22
Kabir Avatar answered Jun 08 '26 17:06

Kabir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!