- Published on
Deep copy of Object using structuredClone in Javascript
When you copy an object in Javascript regularly it'll do only shallow copy which results in the manipulation of original object.
Like:
const originalObject = {
name: {
first:"Ashik",
last: "Nesin"
}
}
const copyObject = {...originalObject}
copyObject.name.first = "Hello" // 'Hello'
console.log(originalObject.name.first) // 'Hello'
Instead we can use structuredClone for our use case.
const originalObject = {
name: {
first:"Ashik",
last: "Nesin"
}
}
const copyObject = structuredClone(originalObject)
copyObject.name.first = "Hello" // 'Hello'
console.log(originalObject.name.first) // 'Ashik'
Happy deep copying!