假设我有一个如下所示的对象:
const state = {
meta: {
attrs: [ 'dude' ],
data: {
foo: 'bar',
stuff: [
'x',
'y',
]
},
},
}
我想将一个对象作为子对象添加到 data
属性中,创建以下内容:
const state = {
meta: {
attrs: [ 'dude' ],
data: {
foo: 'bar',
stuff: [
'x',
'y',
],
hello: 'world',
},
},
}
请注意,在 data
对象中添加 hello: 'world'
作为子项:
使用Object.assign
我知道我可以通过这种方式完成我的任务:
const hello = {
hello: 'world',
}
const data = Object.assign(
{},
state.meta.data,
hello,
)
const meta = Object.assign(
{},
state.meta,
{
data,
},
)
const updatedState = Object.assign(
{},
state,
{
meta,
},
)
是否可以使用更少的 Object.assign
调用来完成此任务?
最佳答案
您可以使用扩展运算符语法以及
const state = {
meta: {
attrs: [ 'dude' ],
data: {
foo: 'bar',
stuff: [
'x',
'y',
]
},
},
}
var data = {
...state, meta: {
...state.meta, data: {
...state.meta.data, hello: 'world'
}
}
}
console.log(data)
关于javascript - 将对象添加到深层嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462320/