How to Copy an Object in JavaScript

Tyler Tyler (258)
0

Making a deep copy of an object in JavaScript is fairly challenging. Fortunately, there are a few ways to accomplish this without much code.

Posted in these interests:

javascript
PRIMARY
51 subscribers
code
86 subscribers
webdev
83 subscribers

jQuery provides an extend method that enables you to create both shallow and deep copies of an object.

// Shallow copy
var newObj = jQuery.extend({}, oldObj);

// Deep copy
var newObj = jQuery.extend(true, {}, oldObj);

A vanilla JavaScript hack that doesn't require much code involves using the JSON library. You can stringify an object and then immediately parse it like this:

var me = {
    name: 'Tyler',
    age: 29
};

var me2 = JSON.parse(JSON.stringify(me));
me2.name = 'Joseph';

console.log(me);
console.log(me2);

This is obviously not the intent of this library, but it works apart from copying functions.