Thanks to native methods for arrays and objects, such as
Object.assign, we are able to create new references for our data copying all the properties/elements in a new instance. But the problem comes when our lists contain nested objects/arrays. Since they are stored in memory with a reference, the implementation of
.assign will just copy that associated address:
So, how can we create a deep copy that always creates new instances of our nested properties?
There are tons of solutions available online, and many libraries like Lodash already provide a solution. But I hope you’ll like my solution. First, it might be useful to understand what happens behind the scenes:
As you can see, it’s pretty simplistic and easy to read, but it does its job well.
It takes an input of any type and returns a new instance, copying all the properties and invoking recursively the function if a nested object/array is found.
Keep in mind that some types don’t necessarily need to be cloned, such as functions or symbols, so it's safe to copy their reference.