DEV Community

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

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

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))
Collapse
 
jasterix profile image
Jasterix

This is helpful. Thanks!!