Cloning an object in javascript
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.
Take a look at the post: What is the most efficient way to clone a javascript object
As per John Resig's answer:
// Shallow copyvar newObject = jQuery.extend({}, oldObject);// Deep copyvar newObject = jQuery.extend(true, {}, oldObject);
More information can be found in the jQuery documentation.
This worked better for me cloning an object using jQuery "parseJSON()" and "JSON.stringify()"
$.ajax({ url: 'ajax/test.html', dataType: 'json', success: function(data) { var objY = $.parseJSON(JSON.stringify(data)); var objX = $.parseJSON(JSON.stringify(data)); }});
Cloning data object in objX & objY are two different object, you do no have to mess up with the "by reference" problem
Gracias!