Native deep cloning of JavaScript objects
Cloning JavaScript objects can be a tricky process, especially when it comes to deep cloning. Deep cloning refers to creating a copy of an object and all of its nested properties, rather than just creating a shallow copy of the object itself. In this article, we’ll explore how to achieve native deep cloning of JavaScript objects using various methods.
Method 1: Using the spread operator
The spread operator (…) can be used to create a shallow copy of an object. However, when it comes to deep cloning, the spread operator falls short, as it only creates a shallow copy of the object’s properties. In order to achieve deep cloning using the spread operator, a recursive approach must be employed to ensure that all nested properties are also deeply cloned.
Method 2: Using JSON.stringify and JSON.parse
Another method for achieving deep cloning of JavaScript objects is using the JSON.stringify and JSON.parse methods. By first converting the object to a JSON string using JSON.stringify, and then parsing it back into a new object using JSON.parse, a deep clone of the original object can be created. However, this method does have its limitations, as it is not suitable for objects that contain functions, symbols, or undefined properties.
Method 3: Using the Lodash library
The Lodash library provides a deepClone method that can be used to achieve native deep cloning of JavaScript objects. This method takes care of the complexities of deep cloning and ensures that all nested properties are deeply cloned without the need for manual recursion. However, it’s important to note that using an external library like Lodash may add unnecessary overhead to your project if deep cloning is the only functionality you require from the library.
In conclusion, achieving native deep cloning of JavaScript objects can be a challenging task. While there are various methods available for deep cloning, it’s important to carefully consider the requirements of your project and the potential drawbacks of each method before deciding on the best approach for your specific use case.
structuredclone is built function??
I never seen that before…
My usual way
const newObj=JSON.parse(JSON.stringify(obj))
Well it's about time