Mike Mike - 1 month ago 17
Javascript Question

How to deep merge instead of shallow merge?

Both Object.assign and Object spread only do a shallow merge.

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 operator only goes one level deep. This is the same with
Object.assign()
.

Is there a way to do this?

Answer

Does anybody know if deep merging exists in the ES6/ES7 spec?

No, it does not.