For example, we have this Object
:
And we want to clone it without affecting the original Object
.
We do not directly assign it. ⚠️
Because every time the original myObject
changes, the clonedObject
will also follow the change and vice versa.
It also applies to Array
.
We need to construct new Object
and put the cloned content into it.
Methods
Deep Copy
This will work for nested-structured original Object
.
For Array
, the slice
or spread operator (...) will shallow-clone the original Array
.
Or:
We can use the similar JSON
method above to achieve deep copy
⚠️ JSON
method limitations:
-
Functions are Lost
Any functions in the object or array are removed completely.
-
undefined
Values are LostProperties with
undefined
are also removed. -
Special Objects Do Not Survive
It only works for plain objects and arrays. Special objects like:
Date
becomes a string (ISO string format).RegExp
becomes an empty object{}
.Map
,Set
,BigInt
, etc., are all lost.
-
Circular References Cause Errors
If the object contains circular references (where one property refers to the object itself),
JSON.stringify()
throws an error.
Shallow Copy: Object.assign()
Method
Shallow Copy: Loop
Nested Object
properties will remain dependent when using either of the shallow copy methods above.
This is the more elaborate conditioning:
Thus, depending the needs, we can either implement deep or shallow copy technique. 🙂
Comments
Post a Comment