loading...

What's the best way to deeply clone an object in JavaScript?

jasterix profile image Jasterix ・1 min read

I recently attempted a code challenge where I needed to deeply clone an object. Prior to this I learned to do this by converting it to JSON. But according to this blog post, he specifically has JSON Serialization as the wrong way to do this.

The reason for this is:

"By doing this you will lose any Javascript property that has no equivalent type in JSON, like Function or Infinity. Any property that’s assigned to undefined will be ignored by JSON.stringify, causing them to be missed on the cloned object.

Also, some objects are converted to strings, like Date objects for example (also, not taking into account the timezone and defaulting to UTC), Set, Map and many others"

Is there a native way to deeply clone an object in JavaScript? The only approach he listed is by using the Lodash library. All of the other methods are shallow copies.

Posted on by:

jasterix profile

Jasterix

@jasterix

Passionate about building great technology and connecting with people to create positive change. Find me elsewhere @jasterix or @_jasterix

Discussion

markdown guide
 

There seems to be no native way, but it is as simple as,

function deepClone(o) {
  /**
   * This excludes null
   */
  if (o && typeof o === 'object') {
    if (Array.isArray(o)) {
      return o.map((a) => deepClone(a))
    } else if (o.constructor === Object) {
      return Object.entries(o).reduce((prev, [k, v]) => ({ ...prev, [k]: deepClone(v) }), {})
    }

    /**
     * Now it depends on how you would recreate the Object, or not...
     */
    return o
  }

  /**
   * BTW, function is another important case you might consider...
   */
  return o
}

A perfect way is simply,

/**
 * Yes, that dangerousLoad
 * js-yaml's dump also supports several options
 */
yaml.load(yaml.dump(o))
 

This is helpful. Thanks!!

 

A library is just a collection of solutions written in a way that they can be reusable. Here is the module in lodash that contains the logic for the deep clone github.com/lodash/lodash/blob/mast..., it's imported from this module github.com/lodash/lodash/blob/mast..., which is the module you would use in your code.

 
const deeplyCloned = object.assign({}, myObj)