Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to clone an object?

I am confused. I create a copy from myObjOne, than i delete an entry from myObjOne and JS delete the entry in my copy(myObjTwo) too? But why?

  myObjOne = {};
  myObjOne['name'] = 'xxx';
  myObjOne['id'] = 'yyy';
  myObjOne['plz'] = 'zzz';  

  // clone
  myObjTwo = myObjOne;

  // remove something
  delete myObjOne['name'];

  console.dir(myObjTwo);

example http://jsbin.com/itixes/edit#javascript,html

like image 710
user970727 Avatar asked Nov 01 '11 11:11

user970727


2 Answers

Update: Removing Object.create as a method of cloning as indicated in comments.

  myObjTwo = myObjOne;

does not clone. It simply copies the reference.

If you want to clone, you can use JSON.parse and JSON.stringify

var x = {a:{b:{c:{'d':'e'}}}};
var y = JSON.parse(JSON.stringify(x));  //y is a clone of x
console.log(y.a.b.c.d); //prints e
console.log(y === x); //prints false

Warning: As Raynos mentioned in comments, this JSON based clone does not retain methods of the input object in the output object. This solution is good enough if your object does not contain any methods. Methods are properties of a object that are functions. If var obj = {add : function(a,b){return a+b;}} then add is a method of obj.

If you need a solution that supports copying of methods, then go through these SO answers (as pointed out by musefan, Matt and Ranhiru Cooray)

  • How do I correctly clone a JavaScript object?
  • What is the most efficient way to deep clone an object in JavaScript?

I would suggest How do I correctly clone a JavaScript object?

like image 198
Narendra Yadala Avatar answered Oct 12 '22 20:10

Narendra Yadala


You can use jQuery like so:

var myObjTwo = jQuery.extend(true, {}, myObjOne);

The first argument indicates that we want to make a deep copy of myObjOne.

like image 36
Nicu Surdu Avatar answered Oct 12 '22 19:10

Nicu Surdu