Some recent work that I’ve been doing has necessitated the ‘cloning’ of objects in Javascript. The objects in question are ‘normal’ objects rather than Function, or constructed objects. Unfortunately this isn’t just a simple case of assigning the contents of one variable to another:

var original = {one: 1, two: 2, three: 3};
var copy = original;

If we did that and then altered or added a property on original, then those changes would apply in copy, because the two variables reference the same object.

Searching the internet turned up How to clone an object in JavaScript by Mikita Manko, which gives a good intro with some naive implementations, why they don’t work; and a final working solution. Unfortunately for my purposes this solution wasn’t quite right. A lot of the objects that I was dealing with contained Array’s, and whilst these are copied as objects, with properties accurately numbered, with the sub-data intact, the copy wasn’t an array. The problem is that typeof is quite a blunt tool which will return a limited set of values.

To get around this we need to be a little bit cleverer. Specifically we need to find the name of an objects type. Restructuring the code a little bit to be more functional results in something that looks like this:

Using the code is very straight forward:

var original = {one: 1, two: 2, three: 3, four: [{five: 5, six: 6}]};
var copy = clone(original);

If you need to deal with objects of other types then just expand the if-else-ladder between lines 25 and 33. Also, it should be noted that this code isn’t used in a production scenario, but was used for a data migration where data fidelity was required.