DEV Community

jatins52
jatins52

Posted on

How to deep copy a nested object in Javascript

How to deep copy a nested object in Javascript

So you have a nested object and let's say you need to copy it to a different variable which is completely different from original one.

How are we doing it today?
Original object:
const obj1 = {name: 'John Smith', address: {mailing: {line1: 'address line 1', line2: 'address line 2', city:'New York'}}};

Copied Object:
Method 1:
using spread operator
const obj2 = {...obj1};
Method 2:
some people would prefer even expensive operation:
const obj2 = JSON.parse(JSON.stringify(obj1));

Problem with method 1 is that spread operator copies the object without reference but it won't do it for nested object e.g. for address key of obj1. So changing obj2.address.line1 will change obj1.address.line1 also.

And method 2 simply looks wrong and expensive.

So how do we do this?
Answer:
const obj2 = structuredClone(obj1);

And now you have created a deep copy of obj1 and obj1 and obj2 are completely different objects.

Note: structuredClone() method is newly available method and might not work in browsers older than March 2022.

This is my first post. Please comment and connect and let me know what I can make better in my next post.

Thank you!!!

Top comments (0)