clone object js code example

Example 1: clone object in js

var student = {name: "Rahul", age: "16", hobby: "football"};

//using ES6
var studentCopy1 = Object.assign({}, student);
//using spread syntax
var studentCopy2 = {...student}; 
//Fast cloning with data loss
var studentCopy3 = JSON.parse(JSON.stringify(student));

Example 2: clone javascript object

let clone = Object.assign({}, objToClone);

Example 3: javascript clone object

var x = {myProp: "value"};
var xClone = Object.assign({}, x);

//Obs: nested objects are still copied as reference.

Example 4: how to clone an object

const first = {'name': 'alka', 'age': 21} 
const another = Object.assign({}, first);

Example 5: javascript clone object

var sheep={"height":20,"name":"Melvin"};
var clonedSheep=JSON.parse(JSON.stringify(sheep));

//note: cloning like this will not work with some complex objects such as:  Date(), undefined, Infinity
// For complex objects try: lodash's cloneDeep() method or angularJS angular.copy() method

Example 6: javascript clone object

let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));