I ran into an issue where i had to make a copy of a JS object in order to compare it to another version of itself and see what differences are there what was added and what was removed and here is a summery of my search.
Shallow copy
In this method we copy the attributes of the object without copying but keeping the reference to the same values in memory so when changing the value in the first object it will change in the second object.
DeepCopy
Same as Shallow copy with one exception, it does not maintain the references to the values in memory hence when changing the value on the first object it does not change the value on the second object.
Method | Pros | Cons |
---|---|---|
shallow copy ( = ) | clear and direct, the default | only shallow copies objects |
JSON.stringify() and JSON.parse() | deep copies nested objects | doesn’t copy functions |
Object.assign() | copies the immediate members of an object—including functions | doesn’t deep copy nested objects |
the … spread operator | simple syntax, the preferred way to copy an object | doesn’t deep copy nested objects |
Lodash cloneDeep() | clones nested objects including functions | adds an external dependency to your project |
structuredClone() | clones nested objects including functions |
Copying using the equals operator
This is a shallow copy method, it does not copy nested objects or functions.
Copying using JSON
This is a deep copy method the copies nested object but not nested functions. Even tho this method is highly used (due to the lack of an alternative up to 2023) but it’s not recommended.
Copying using Object.assign()
It copies the immediate members of an object—including functions but does not copy nested object/functions.
Copying using … operator
Usually this is the preferred method to copy objects but does not copy nested object/functions.
Copying using Lodash
Clones nested objects including functions but on the downside it adds an external dependency to your project.
Copying using structuredClone()
Finally a built in function in JS was added, that clones nested objects including functions using the The structured clone algorithm which supports multiple types.