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);
1let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
1//returns a copy of the object
2function clone(obj) {
3 if (null == obj || "object" != typeof obj) return obj;
4 var copy = obj.constructor();
5 for (var attr in obj) {
6 if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
7 }
8 return copy;
9}