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);
JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.
assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
Use the Object. assign() Method to Clone an Object in TypeScript. The Object. assign() works similarly as in the case of the spread operator and can be used to clone simple objects, but it fails in the case of nested objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With