Friday, 10 July 2020

spread syntax or Object.assign() in Javascript

Object.assign() will only do a shallow copy and will only enumerate own props.

shallow copy using "Spread Synatx" or "Object.assign"

Spread syntax to copy/merge an object.

var obj = { foo : "foo", bar:"bar"};
var clonedobj= {...obj};

The Object.assign() method can be used to copy the values of all enumerable own properties
from one or more source objects to a target object, and it will return the target object

var obj= {foo:"foo",bar:"bar"};
var clonedObj=Object.assign({},obj);

Both spread syntax or Object.assign() used to copy/merge the enumerable properties
of an object to another object.

Note the empty {} as the first argument, this will ensure you don't mutate the original object.

Note : Problem with these two approaches is that it will just do the shallow copy.

Deep Copy :
Deep copy using JSON.stringify and JSON.parse

ex :

// Deep Clone
  obj = { a: 0 , b: { c: 0}};
  let deepClone = JSON.parse(JSON.stringify(obj));
  obj.a = 5;
  obj.b.c = 5;
  console.log(JSON.stringify(obj)); // { a: 5, b: { c: 5}}
  console.log(JSON.stringify(deepClone)); // { a: 0, b: { c: 0}}
  
  deepClone.a = 6;
  deepClone.b.c = 6;
  console.log(JSON.stringify(obj)); // { a: 5, b: { c: 5}}
  console.log(JSON.stringify(deepClone)); // { a: 6, b: { c: 6}}

1.Javascript objects are mutable and store by reference.
2.Object.assign() and spread syntax can be used for copy but it will be shallow copy.
3.JSON.stringify and JSON.parse can be used for deep copy.

No comments:

Post a Comment