Cloning an object in javascript

Matrym picture Matrym · Mar 19, 2011 · Viewed 91.3k times · Source

The below first logs 0, and then logs 1. How do I store a copy of the object, rather than a reference to it?

debug.log(vi.details.segment);
vi.nextSegment = vi.details;
vi.nextSegment.segment++;
debug.log(vi.details.segment);

Answer

Mike Lewis picture Mike Lewis · Mar 19, 2011

To clone an object in jQuery:

var vi.nextSegment = jQuery.extend({}, vi.details);

NOTE: The above is a shallow copy: any nested objects or arrays will be copied by reference - meaning any changes you make to vi.nextSegment.obj[prop] will be reflected in vi.details.obj[prop]. If you want a completely new object which is completely separate from the original, you will need to do a deep copy (pass true as the first parameter):

var vi.nextSegment = jQuery.extend(true, {}, vi.details);

To read up more on extend, see here.