HomeCategoriesAll Tags

Finally we have a perfect way to deep copy js object

Getting errors due to shallow copy? Here's the perfect modern way to deep copy a json object...

Did you hear about structuredClone()?

const original = {
  title: 'Championship',
  name: ['Ayush'],
  date: new Date(123),
  address: new Map([
    ['city', 'Mumbai'],
    ['state', 'Maharashtra'],
  ]),
}

// 😍
const copied = structuredClone(original)

structuredClone is the modern weapon in your arsenal to create a deep copy a json object. It is now a native way in javascript.

  • It will clone nested objects and arrays.
  • It will clone variety of data types such as Date, Set, Map, ArrayBuffer, Blob, File, Error, everything js-built-in or web/API types.

Do not go for shallow copy

const shallowCopy = { ...foo }
const shallowCopy = Object.assign({}, foo)
const shallowCopy = Object.create(foo)

Because the nested objects and arrays will still have a shared reference with the shallow copy. So, if you modify the shallow copy then original object will also get modified.

Even JSON.parse(JSON.stringify(x)) is not ideal

Because JSON.stringify can only handle basic objects, arrays, and primitives. So in the copied object Date object from original will change to a string. Set and Map types are also not copied correctly and undefined is simply ignored. So avoid doing this.

What about lodash's cloneDeep?

That's fine and does as intended but why to include unnecessary code when browsers now have the native solution.

Hope this was helpful. Thanks!!

- Ayush 🙂