Skip to main content

JavaScript: Copy Object

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 Lost

    Properties 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.

Thus, depending the needs, we can either implement deep or shallow copy technique 🙂

River Copier

Or, we can use this:

Or, we can sing a blues song:

🎸 Dilly Lost His Functions Again 🎶

(Key of E, slow blues shuffle)


[Verse 1]

Dilly was a copier, lived down by the stream

Short-circuited his motherboard, lost all of his dreams

They tried to clone his spirit, with JSON in their hands

But Dilly lost his functions, now he barely understands


[Chorus]

🎶 Ohhh, Dilly lost his functions again

He’s a hollowed-out machine, no methods left to mend

A deep copy’s betrayal, left him cold in the rain

Dilly lost his functions… now he’s circlin’ the drain 🎶


[Verse 2]

Billy tried to fix him, with a loop and a prayer

But functions can’t be serialized, nobody seemed to care

His date turned into a string, his regex turned to dust

In the JSON deep-clone nightmare, Dilly lost all his trust


[Chorus]

🎶 Ohhh, Dilly lost his functions again

His callbacks are all broken, no events left to send

A deep copy’s a killer, when you need a loyal friend

Dilly lost his functions… will he ever mend? 🎶


[Bridge]

Now he floats down the river, with a photocopied heart

Half machine, half legend, torn apart

If you see a blinking light, down by the bend

That’s just Dilly printing error logs… at the bitter end


[Final Chorus]

🎶 Ohhh, Dilly lost his functions again

He’s a ghost in the memory, on a loop without end

In the land of deep copies, where objects can’t pretend

Dilly lost his functions… but he’ll always transcend 🎶

Last modified on

Comments