Create a deep clone of an object in JavaScript
This post will discuss how to create a deep clone of an object in JavaScript.
A deep copy means that the new object will have its own copies of the properties and values of the original object, so changing one will not affect the other. To create a deep clone of an object in JavaScript, we need to copy not only the properties and values of the object, but also any nested objects or arrays that the object may contain. There are several ways to do this, depending on the complexity and structure of the object. Here are some of the common functions:
1. Using JSON.parse() and JSON.stringify() functions
One simple and fast way to create a deep clone of an object in JavaScript is to use the JSON functions. It works by converting the object to a JSON string using JSON.stringify(), and then parsing the JSON string back to an object using JSON.parse(), creating a new copy of the object with the same values and structure. For example, this code creates a copy of an object with three properties: a, b, and c.
|
1 2 3 4 |
let obj = {a: 1, b: 2, c: 3}; let objCopy = JSON.parse(JSON.stringify(obj)); console.log(objCopy); // { a: 1, b: 2, c: 3 } |
However, this function has some limitations and drawbacks. For example, it cannot handle functions, dates, symbols, undefined, or circular references. It also does not preserve the prototype chain or the constructor of the object.
2. Using a recursive function
This is a more flexible and robust way to create a deep clone of an object that can handle various types of values, such as functions, dates, symbols, undefined, or circular references. This function works by creating a custom function that iterates over the properties of the object and copies them to a new object. If the value of a property is an object or an array, the function calls itself recursively to copy the nested values. Here’s an example of this approach:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// Define a function that creates a deep clone of an object function deepCopy(obj) { // Check if the obj is null or not an object if (obj === null || typeof obj !== "object") { // Return the obj as it is return obj; } // Create an empty object or array to store the clone let clone = Array.isArray(obj) ? [] : {}; // Loop over the properties or elements of the obj for (let key in obj) { // Get the value of the property or element let value = obj[key]; // If the value is an object or an array, call the function recursively // to copy the nested values if (typeof value === "object") { value = deepCopy(value); } // Assign the key and the value to the clone clone[key] = value; } // Return the clone return clone; } // create an object let obj = { a: 1, b: 2, c: 3}; // deep copy let objCopy = deepCopy(obj); console.log(objCopy); // { a: 1, b: 2, c: 3 } |
However, this function may result in some performance issues if the object is very large or complex. It also does not preserve the prototype chain or the constructor of the object.
3. Using structuredClone() global function
This is a modern way to deep copy an array in JavaScript, that supports more data types than the JSON object functions. The structuredClone() function creates a structured clone of the array, which means it preserves the internal structure and references of the original array.
|
1 2 3 4 5 6 7 |
// create an object let obj = {a: 1, b: 2, c: 3}; // create a deep clone of the object using structuredClone let objCopy = structuredClone(obj); console.log(objCopy); // { a: 1, b: 2, c: 3 } |
The structuredClone() function can clone an object that is structured-cloneable, which means that it only contains values that can be serialized and deserialized by the structured clone algorithm. These values include primitive types (string, number, bigint, boolean, undefined, symbol, and null), objects, arrays, dates, maps, sets, regexes, blobs, files, and array buffers. However, it cannot handle functions, functions, DOM elements, errors, or objects with non-enumerable or accessor properties. If our object contains any of these values, we need to either remove them or replace them with structured-cloneable values before cloning.
4. Using a library
This is a convenient and reliable way to create a deep clone of an object that can handle most types of values and cases. There are many libraries that provide this functionality, such as Lodash, Underscore, Ramda, etc. These libraries offer various options and features for creating and manipulating objects, such as preserving prototypes, constructors, customizers, etc. The following code creates a deep copy of an object using the cloneDeep() function from the Lodash library. This function works by simply passing the object as the first argument, and the copy will be returned.
|
1 2 3 4 5 6 7 8 9 10 |
// import Lodash const _ = require("lodash"); // create an object let obj = {a: 1, b: 2, c: 3}; // use _.cloneDeep to create a deep copy let objCopy = _.cloneDeep(obj); console.log(objCopy); // { a: 1, b: 2, c: 3 } |
That’s all about creating a deep clone of an object in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)