DEV Community

loading...
Cover image for Cloning objects in JavaScript

Cloning objects in JavaScript

Adam K Dean
Blockchain Lead. Hacker. Founder. Amateur Radio, and all things engineering.
・1 min read

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?

Discussion (0)