Both Object.assign and Object spread only do a shallow merge.
(Object.assign和Object Spread都仅进行浅合并。)
An example of the problem:
(问题的一个示例:)
// No object nesting
const x = { a: 1 }
const y = { b: 1 }
const z = { ...x, ...y } // { a: 1, b: 1 }
The output is what you'd expect.
(输出是您期望的。)
However if I try this:(但是,如果我尝试这样做:)
// Object nesting
const x = { a: { a: 1 } }
const y = { a: { b: 1 } }
const z = { ...x, ...y } // { a: { b: 1 } }
Instead of
(代替)
{ a: { a: 1, b: 1 } }
you get
(你得到)
{ a: { b: 1 } }
x is completely overwritten because the spread syntax only goes one level deep.
(x完全被覆盖,因为传播语法仅深入了一层。)
This is the same withObject.assign()
.(这与Object.assign()
相同。)
Is there a way to do this?
(有没有办法做到这一点?)
ask by Mike translate from so