This content originally appeared on DEV Community and was authored by Raju Saha
I am writing this article because I recently posted an article regarding Shallow Copy and Deep Copy. I wanted to jot down what I was doing until now and highlight a better approach for deep cloning objects, especially when dealing with nested keys containing non-string or non-number data.
Previously, I was using the method JSON.parse(JSON.stringify(object))
for deep cloning. However, this approach often falls short when the nested key has different data types, requiring manual assignment for those particular key values.
Thanks to @jonrandy and @jahid6597 for shedding light on a better solution introduced in 2022: the structuredClone()
function. This global function uses the structured clone algorithm to create a deep clone of an object, handling various data types more effectively.
The structuredClone()
method also supports transferable objects. In such cases, the transferable objects in the original value are transferred rather than cloned to the new object. These transferred objects are detached from the original and attached to the new object, making them inaccessible to the original object.
Example
Below, we use JSON.parse and JSON.stringify for cloning the object.
However, notice that when it's logged, the 'eighth' key is not shown.
To address the above issue, we can use the structuredClone() global function for a deep copy.
The structuredClone()
method is supported by modern browsers and can handle transferable objects efficiently.
For more details, please refer to the official documentation.
This content originally appeared on DEV Community and was authored by Raju Saha
Raju Saha | Sciencx (2024-06-24T14:51:08+00:00) Stop Using JSON.parse(JSON.stringify(object)) for Deep Cloning! Try This Instead. Retrieved from https://www.scien.cx/2024/06/24/stop-using-json-parsejson-stringifyobject-for-deep-cloning-try-this-instead/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.