本文介绍了使用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: ''
}
}
}
我更新的对象如下:
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更新嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!