DEV Community

Cover image for Cloning objects in JavaScript
Adam K Dean
Adam K Dean

Posted on

Cloning objects in JavaScript

Just a quick snippet post today.

A great way to clone objects in JavaScript and break references is to serialize and deserialize the object. The process of converting it to a JSON string and back into an object severs any references. Unfortunately, it also breaks certain types such as Date and probably RegEx too.

var clone = JSON.parse(JSON.stringify(original));
Enter fullscreen mode Exit fullscreen mode

A better way (I've found) to clone objects while retaining types is to use jQuery.extend.

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
Enter fullscreen mode Exit fullscreen mode

There are other, quicker ways, but when you can run 120,000 deep copies a second, is that extra microsecond really worth it?

Latest comments (0)