使用 Object.assign 更新嵌套对象 [英] Update nested object using Object.assign
问题描述
我有以下对象.当用户点击按钮时,该对象会被分配一个新值.
I have the following object. This object gets assigned a new value when the user clicks on a button.
state = {
title: '',
id: '',
imageId: '',
boarding: {
id: '',
test: '',
work: {
title: '',
id: ''
}
}
}
我更新的对象看起来像:
My updated object looks like:
state = {
title: 'My img',
id: '1234',
imageId: '5678-232e',
boarding: {
id: '0980-erf2',
title: 'hey there',
work: {
title: 'my work title',
id: '456-rt3'
}
}
}
现在我只想更新状态内的工作对象并保持一切不变.我使用 Object.assign()
当对象没有嵌套但混淆嵌套.
Now I want to update just work object inside state and keep everything the same. I was using Object.assign()
when the object was not nested but confused for nesting.
Object.assign({}, state, { work: action.work });
我的 action.work 拥有整个工作对象,但现在我想将其设置为登机,但这会替换登机中的所有内容,而这不是我想要的.
My action.work has the entire work object but now I want to set that to boarding but this replaces everything that is in boarding which is not what I want.
推荐答案
您应该手动合并深层对象属性,请尝试以下操作:
You should manually merge deep object properties, try following:
Object.assign({}, state, {
boarding: Object.assign({}, state.boarding, {
work: action.work
}
});
或使用扩展运算符
{
...state,
boarding: {
...state.boarding,
work: action.work
}
}
这篇关于使用 Object.assign 更新嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!