Deep Clone Object

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create a deep clone of an object in JavaScript. We will use recursion to clone primitives, arrays, and objects while excluding class instances. By the end of this lab, you will be able to create a complete copy of an object without altering the original.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28260{{"`Deep Clone Object`"}} javascript/data_types -.-> lab-28260{{"`Deep Clone Object`"}} javascript/arith_ops -.-> lab-28260{{"`Deep Clone Object`"}} javascript/comp_ops -.-> lab-28260{{"`Deep Clone Object`"}} javascript/cond_stmts -.-> lab-28260{{"`Deep Clone Object`"}} javascript/array_methods -.-> lab-28260{{"`Deep Clone Object`"}} javascript/obj_manip -.-> lab-28260{{"`Deep Clone Object`"}} javascript/destr_assign -.-> lab-28260{{"`Deep Clone Object`"}} end

Instructions to Deep Clone an Object

To deep clone an object, follow these steps:

  1. Create a new terminal/SSH instance and type node to start practicing coding.
  2. Use recursion to clone primitives, arrays, and objects, excluding class instances.
  3. Check if the passed object is null and, if so, return null.
  4. Use Object.assign() and an empty object ({}) to create a shallow clone of the original.
  5. Use Object.keys() and Array.prototype.forEach() to determine which key-value pairs need to be deep cloned.
  6. If the object is an Array, set the clone's length to that of the original and use Array.from() to create a clone.
  7. Use the following code to implement deep cloning:
const deepClone = (obj) => {
  if (obj === null) return null;
  let clone = Object.assign({}, obj);
  Object.keys(clone).forEach(
    (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;
};

Use the following code to test your deep cloning function:

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

Summary

Congratulations! You have completed the Deep Clone Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like