1var student = {name: "Rahul", age: "16", hobby: "football"};
2
3//using ES6
4var studentCopy1 = Object.assign({}, student);
5//using spread syntax
6var studentCopy2 = {...student};
7//Fast cloning with data loss
8var studentCopy3 = JSON.parse(JSON.stringify(student));
1const target = { a: 1, b: 2 };
2const source = { b: 4, c: 5 };
3
4const returnedTarget = Object.assign(target, source);
5
6console.log(target);
7// expected output: Object { a: 1, b: 4, c: 5 }
8
9console.log(returnedTarget);
10// expected output: Object { a: 1, b: 4, c: 5 }
11
1var x = {myProp: "value"};
2var xClone = Object.assign({}, x);
3
4//Obs: nested objects are still copied as reference.
1const first = {'name': 'alka', 'age': 21}
2const another = Object.assign({}, first);
1var sheep={"height":20,"name":"Melvin"};
2var clonedSheep=JSON.parse(JSON.stringify(sheep));
3
4//note: cloning like this will not work with some complex objects such as: Date(), undefined, Infinity
5// For complex objects try: lodash's cloneDeep() method or angularJS angular.copy() method
1let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));