Published on

Deep Copy Js

Shallow copy

Using the object spread operator ... to shallow copy.

const objectA = {
  a: 1,
  b: 2,
}
const cloneA = { ...objectA }

Deep copy

Using JSON.stringify

const objectA = {
  a: 1,
  b: 2,
}
const deepCloneA = JSON.parse(JSON.stringify(objectA))

Structured clone

Using structuredClone. The global structuredClone() method creates a deep clone of a given value using the structured clone algorithm.

const objectA = {
  a: 1,
  b: 2,
}
const deepCloneA = structuredClone(objectA)