Is this a good way to clone an object in ES6?

Dmitry Fadeev picture Dmitry Fadeev · Sep 28, 2016 · Viewed 126k times · Source

Googling for "javascript clone object" brings some really weird results, some of them are hopelessly outdated and some are just too complex, isn't it as easy as just:

let clone = {...original};

Is there anything wrong with this?

Answer

Mark Shust at M.academy picture Mark Shust at M.academy · Sep 12, 2017

This is good for shallow cloning. The object spread is a standard part of ECMAScript 2018.

For deep cloning you'll need a different solution.

const clone = {...original} to shallow clone

const newobj = {...original, prop: newOne} to immutably add another prop to the original and store as a new object.