Deep clone an object in JavaScript

Deep cloning an object in JavaScript was natively added in Node 17.

Deep clone an object using structuredClone

Deepling cloning an object is completed using structuredClone.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const a = {
  col1: 'val1',
  col2: {
      nestedObjected: {
          col1: 'val1'
      }
  }
}

const b = structuredClone(a);
console.log(b); 
// {"col1":"val1","col2":{"nestedObjected":{"col1":"val1"}}}

Deep clone an object using JSON

If the structuredClone method is not available and the user does not want to add an external library, using JSON may satisfy the requirement. If the following types are not used:

  • Date
  • undefined
  • Infinity
  • Regular expressions
  • Maps
  • Sets
  • Blobs
  • other compex types within an object

a simple one liner may be sufficient.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const a = {
  col1: 'val1',
  col2: {
      nestedObjected: {
          col1: 'val1'
      }
  }
}

const b = JSON.parse(JSON.stringify(a))
console.log(b); 
// {"col1":"val1","col2":{"nestedObjected":{"col1":"val1"}}}