Object deep copy in JavaScript

Object deep copy in JavaScript

We now have an answer for the use cases where we want to do a deep copy on an object but we had to rely on a library like lodash or underscore, it's called structuredClone and it can be used without needing any extra libraries.

Problem

I'm sure that at least once in your JavaScript programmer life you've encountered an issue with deep copies of objects. For example, you have an object and you try to create a copy of it but every time you modify a property in the copy, the same property is modified in the original object so you can't keep a before and after state for the same object.

Existing Solutions

OK, I have the same problem, what are the options?

  1. JSON stringify/parse - This was one of the most used solutions to deep copy an object and make sure we lost the reference between them. What you need to do is stringify the object and then parse it to make it an object again, this way you'll make sure you have a completely distinct copy.

     const originalObject = {
       a: 1,
       b: {
         c: 2,
         d: {
           e: 3
         }
       }
     };
     const copiedObject = JSON.parse(JSON.stringify(initialState));
    
  2. Lodash - As with everything else related to JavaScript, if there's a problem, most likely there's a library for it. In this case, we have Lodash and its cloneDeep function. Here's how it works:

     const _ = require('lodash'); // Import Lodash
    
     const originalObject = {
       a: 1,
       b: {
         c: 2,
         d: {
           e: 3
         }
       }
     };
    
     const copiedObject = _.cloneDeep(originalObject);
    
  3. Underscore.js - Another library similar to Lodash that has a clone function that needs to receive an extra parameter to enable deep copying. As you'll see in the example below, the clone() function receives a boolean as a second parameter and if the boolean is true then we'll make a deep clone of the object.

     const _ = require('underscore');
    
     const originalObject = {
       a: 1,
       b: {
         c: 2,
         d: {
           e: 3
         }
       }
     };
    
     const copiedObject = _.clone(originalObject, true);
    

A new and improved method

We now can use structuredClone() which is a global method that allows the new object to be completely detached from the original.

const originalObject = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3
    }
  }
};

const copiedObject = structuredClone(originalObject);

According to the method's specifications, it's available with full support starting with Chrome v98.

Let me know what you think.