← Back to Upcase

Cloning an object in Javascript

(Jon Seidel) #1

What’s the recommended method for cloning an object in native JavaScript? I found several references on the web (such as this one: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object/728694#728694) which seem rather complicated.

FYI I don’t have jQuery in this repo (maybe I should) so can’t do the jQuery.extend dance.

Update: turns out there’s an easy way to handle this (as long as you don’t need a deep copy; thanks to David Walsh):

var ary = [1,2,3];
var ar2 = ary.slice(0);

The String object also has a slice() method, so it works there as well.

This approach also works, but is decidedly more klunky although maybe a bit more obvious:

var ary = [1,2,3];
var ar2 = new Array().concat(ary);