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.
This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 92% completion rate. It has received a 100% positive review rate from learners.
Instructions to Deep Clone an Object
To deep clone an object, follow these steps:
- Create a new terminal/SSH instance and type
nodeto start practicing coding. - Use recursion to clone primitives, arrays, and objects, excluding class instances.
- Check if the passed object is
nulland, if so, returnnull. - Use
Object.assign()and an empty object ({}) to create a shallow clone of the original. - Use
Object.keys()andArray.prototype.forEach()to determine which key-value pairs need to be deep cloned. - If the object is an
Array, set theclone'slengthto that of the original and useArray.from()to create a clone. - 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.