Saturday, August 6, 2016

Clone/Copy JavaScript Object

Creating an Object copy from an object was not easy earlier in JavaScript (before ECMAScript 2015). Now as ECMA 2015 is available we can use Object.assign to create copy of an object.

Create clone/copy of an object before ECMAScript 2015

 var obj1 = {a:1,b:2}, obj2;
 // one simple way is to stringify and then use
 obj2 = JSON.parse(JSON.stringify(obj1));
 console.log(obj2); // {a:1,b:2} 

Clone/Copy after ECMAScript 2015

Now ECMAScript 2015 provided assign method in Object so that we can create clone/copy of an object. For method is available chrome 45 onwards.

 var obj1 = {a:1,b:2}, obj2;
 obj2 = Object.assign({}, obj1);
 console.log(obj2); // {a:1,b:2}
 
 // another way to use same method (assign)
 var obj3={x:1, y:2}, obj4 = {};
 Object.assign(obj4,obj3);
 console.log(obj4);

No comments:

Post a Comment