Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning an object in JavaScript

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); 
like image 231
Matrym Avatar asked Mar 19 '11 20:03

Matrym


People also ask

How many ways can you clone an object in JavaScript?

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.

How do you deep copy an object in JavaScript?

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.

How do you clone an object in TypeScript?

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.


1 Answers

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.

like image 136
Mike Lewis Avatar answered Sep 24 '22 12:09

Mike Lewis