loading...

re: What's the best way to deeply clone an object in JavaScript? VIEW POST

FULL DISCUSSION
 

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!!

code of conduct - report abuse