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));
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));
1const person = {
2 firstName: 'John',
3 lastName: 'Doe'
4};
5
6
7// using spread ...
8let p1 = {
9 ...person
10};
11
12// using Object.assign() method
13let p2 = Object.assign({}, person);
14
15// using JSON
16let p3 = JSON.parse(JSON.stringify(person));