更新for循环内的Javascript对象属性

bru*_*ruh 1 javascript

我正在尝试用另一个看似微不足道的对象更新 JS 对象,但该值并未更新。

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)
Run Code Online (Sandbox Code Playgroud)

看起来,student只是一些浮动的东西,与userData我试图更新其值的点无关。但是,我不知道如何进行更新或我缺少什么。

编辑:预期的输出是一旦找到student对象sampleObj就将其替换。

con*_*exo 7

forEach(el, index)改为使用,以便您拥有可用于更新的索引:

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)
Run Code Online (Sandbox Code Playgroud)


Kab*_*bir 6

数组项替换不是这样工作的。相反,您可以像这样替换学生对象的属性

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

它将把 samplObj 的所有属性分配给学生对象。