JavaScript: Clone/Deep Copy an Object

There is a common gotcha that programmers making a copy of object in javascript with setting two variables copy and original equal to the same object sourceObject.

It actually creates a reference pointing to that same object. Both variables copy and original can reach into the contents of “sourceObject”. Any changes or updates properties on copy and original also changes the sourceObject itself.

To create a complete clone with no prototype references back to the source object, the deep copy to clone the object MUST be introduced.

A deep copy will recursively clone every objects it encounters. The clone and the original object will not share anything, so the clone will be a fully distinct entity.

1. Plain old javascript object – JSON

For plain old JavaScript objects, the good way to clone an object in modern runtimes is using JSON parse and stringify. It is at least one way we can make an actual copy of the source object. Also we can then change the copy without destroying our source object.

Note that the source object must be a pure JSON object. This is to say, all of its nested properties must be scalars (like boolean, string, array, object, etc). Any function or special objects like RegExp or Date will not be cloned.

This approach is just simple and easy to implement. Wrap it into a convenience function and if you really need to squeeze out some gain, go for at a later time. It is works best after testing all kinds of cloning methods.

2. Non-plain JavaScript objects

For non-plain JavaScript objects, there isn’t a really simple answer currently. In fact, there can’t be because of the dynamic nature of JavaScript functions and inner object state. Deep cloning a JSON structure with functions inside requires you recreate those functions and their inner context. And JavaScript simply doesn’t have a standardised way of doing that.

The correct way to implement is via a convenience method that you declare and reuse within your code. The convenience method can be endowed with some understanding of your own objects so you can make sure to properly recreate the graph within the new object.

The Dojo Toolkit provides an excellent function for cloning just about anything. This clone function will deep clone nodes, object literals, arrays, dates, regular expressions, and generic objects:

The main idea is that you need to special handle the instantiation of your functions (or prototypal classes, so to speak) on a per-type basis. Here, he’s provided a few examples for RegExp and Date.

Not only is this code brief but it’s also very readable. It’s pretty easy to extend.

Other cloning an Object

Resource:

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA