我试图用另一个看似微不足道的对象来更新JS对象,但该值未更新。
MIN(ID_CMP)
似乎SELECT
只是一些浮动的东西,在我试图更新其值时与ORDER BY
无关。但是,我不知道如何进行更新或丢失了什么。
编辑:预期的结果是一旦找到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)
对象,就将student
替换为userData
。
答案 0 :(得分:3)
请改用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)
答案 1 :(得分:3)
替换阵列项目不起作用。相反,您可以像这样替换学生对象的属性
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);
}
}
}
它将把samplObj的所有属性分配给学生对象。
答案 2 :(得分:1)
您永远不会更新实际的userData
。要对其进行更新,应在循环中引用userData
对象,而不是用于迭代该对象的临时变量。
因此,请尝试以下操作:
let sampleObj = { id: 1, name: 'Kelly' }
let userData = [
{
students: [
{ id: 1, name: 'Sandra' }
]
},
{
students: [
{ id: 2, name: 'Jerome' }
]
}
]
let j=0
for ( let group of userData ) {let i=0
for ( let student of group.students ) {
if ( student.id === sampleObj.id ) {
console.log('updating student object')
userData[j].students[i] = sampleObj
// student = { ...sampleObj } (another failed attempt)
// userData[group].students[student] = sampleObj (another failed attempt)
} i++;
} j++;
}
console.log('userData', userData)