structuredClone method is built-in:
structuredClone method serves as a powerful tool for creating exact, deep copies of complex data structures and objects within the language. Unlike conventional cloning methods,
structuredClone can duplicate not only simple data types but also intricate objects, arrays, and nested elements, ensuring their integrity while preserving references. Whether dealing with intricate data structures or nested objects,
- And many more
This hack works perfectly well for all situations, but still has some drawbacks, which are addressed by the
The above example we are trying to use the hack to copy the
song object with a key which is of type
Date but when we try to log the copied object we get the following:
releaseDate key is converted to string and is not the desired result, we want the
Date to remain as a
Understanding what a deep copy means is important here, if we want a shallow copy the spread operator serves the purpose, basically not being able to copy the nested elements of an object.
The above works perfectly fine. Until, we introduce a third key to our
song object and try to copy it usign the spread method.
Lets look at the same example again with some change, here when we try to push a string value to the
tags key on the
shallowCopiedSong object, not only it will add
'rick roll' to
shallowCopiedSong it will also add it to the
song object, and that is not the solution we are looking for.