29/10/2024
When working with objects in JavaScript, it's important to understand the difference between deep cloning and shallow cloning. Shallow cloning creates a new object that copies over the references of the original object's properties, while deep cloning ensures that all nested properties are replicated, creating entirely new instances of those objects.
To make this clearer, let’s look at an example:
const original = { name: "Alice", address: { city: "Wonderland", zip: 12345 } }; const shallowClone = Object.assign({}, original); shallowClone.address.city = "New Town"; console.log(original.address.city); // Outputs: "New Town"
In the code above, modifying shallowClone.address.city
also changes original.address.city
because both objects share the same reference for the nested address
object. To prevent this, we need to perform a deep clone.
The simplest way to deep clone an object is by using JSON.parse
and JSON.stringify
. However, this method comes with some limitations:
const deepCloneJSON = (obj) => { return JSON.parse(JSON.stringify(obj)); }; const clonedObject = deepCloneJSON(original); clonedObject.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"
Limitations:
For more control, we can write a recursive function that copies properties manually:
const deepCloneRecursive = (obj) => { if (obj === null || typeof obj !== 'object') { return obj; // Return the value if obj is not an object } const clone = Array.isArray(obj) ? [] : {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { clone[key] = deepCloneRecursive(obj[key]); // Recursively clone properties } } return clone; }; const clonedRecursiveObject = deepCloneRecursive(original); clonedRecursiveObject.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"
If you're working on a project where you already have Lodash included, it has a built-in function for deep cloning:
const _ = require('lodash'); const clonedWithLodash = _.cloneDeep(original); clonedWithLodash.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"
Lodash’s cloneDeep
method handles various data types and is optimized for performance.
In modern browsers, you can use the newer structuredClone
function, which is efficient for cloning many types of objects.
const clonedStructured = structuredClone(original); clonedStructured.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"
Advantage:
Understanding deep cloning is crucial when manipulating JavaScript objects, particularly when nested structures are involved. Choose the method that fits your needs, considering the data types and structures you are working with. Happy coding!
29/10/2024 | VanillaJS
17/11/2024 | VanillaJS
17/11/2024 | VanillaJS
17/11/2024 | VanillaJS
17/11/2024 | VanillaJS
29/10/2024 | VanillaJS
17/11/2024 | VanillaJS