Getting errors due to shallow copy? Here's the perfect modern way to deep copy a json object...
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.
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.
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.
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 🙂