how.wtf

Deep clone an object in JavaScript

· Thomas Taylor

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.

 1const a = {
 2  col1: 'val1',
 3  col2: {
 4      nestedObjected: {
 5          col1: 'val1'
 6      }
 7  }
 8}
 9
10const b = structuredClone(a);
11console.log(b); 
12// {"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:

a simple one liner may be sufficient.

 1const a = {
 2  col1: 'val1',
 3  col2: {
 4      nestedObjected: {
 5          col1: 'val1'
 6      }
 7  }
 8}
 9
10const b = JSON.parse(JSON.stringify(a))
11console.log(b); 
12// {"col1":"val1","col2":{"nestedObjected":{"col1":"val1"}}}

#Javascript  

Reply to this post by email ↪