solvit.io

Clone a JavaScript object into a new object

Solution #1
var clonedObject = Object.assign({}, originalObject);
  • This solution requires ECMAScript 2015 (ES6).
  • The assign() method just copies enumerable and own properties from a source object to a target object invoking getters and setters.
  • This solution is not valid for "deep cloning" objects.
Example
var object = { foo: 'bar' };
var clone = Object.assign({}, object);
// clone = { foo: 'bar' };
Solution #2
var clonedObject = JSON.parse(JSON.stringify(originalObject));
  • This solution is valid for "deep cloning", but it doesn't work for Date objects.
  • If the original object contains Date objects, they are represented as strings in the cloned object.
Example
var object = { foo: 'bar' };
var clone = JSON.parse(JSON.stringify(object));
// clone = { foo: 'bar' };
Find more solutions about: , ,