Deep clone object

JavaScript, Object, Recursion · Oct 22, 2020

Creates a deep clone of an object. Clones primitives, arrays and objects, excluding class instances.

  • Use recursion.
  • Check if the passed object is null and, if so, return null.
  • Use Object.assign() and an empty object ({}) to create a shallow clone of the original.
  • Use Object.keys() and Array.prototype.forEach() to determine which key-value pairs need to be deep cloned.
  • If the object is an Array, set the clone's length to that of the original and use Array.from() to create a clone.
const deepClone = obj => {
  if (obj === null) return null;
  let clone = Object.assign({}, obj);
    key =>
      (clone[key] =
        typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
  if (Array.isArray(obj)) {
    clone.length = obj.length;
    return Array.from(clone);
  return clone;

const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj

More like this

  • JavaScript Object Cloning

    Easily clone JavaScript objects and arrays using various techniques.

    Collection · 4 snippets

  • How do I clone an object in JavaScript?

    Learn how JavaScript handles mutable data, such as objects and arrays, and understand how shallow cloning and deep cloning work.

    JavaScript, Object · Jun 12, 2021

  • Compact object

    Deeply removes all falsy values from an object or array.

    JavaScript, Object · Nov 27, 2020

  • Deep map object keys

    Deep maps an object's keys.

    JavaScript, Object · Sep 15, 2020