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 = {key: 'value'}
2var y = JSON.parse(JSON.stringify(x))
3
4//this method actually creates a reference-free version of the object, unlike the other methods
5//If you do not use Dates, functions, undefined, regExp or Infinity within your object
1var x = {myProp: "value"};
2var xClone = Object.assign({}, x);
3
4//Obs: nested objects are still copied as reference.
1let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
1// syntax: let <newObjectName> = {...<initialObjectName>};
2
3// example:
4const me = {
5 name: 'Jakes',
6 age: 30,
7};
8const friend = {...me};
9friend.age = 27;
10console.log(friend.age); // 27
11console.log(me.age); // 30
12
13// -----------------------------
14// BAD
15// -----------------------------
16const me = {
17 name: 'Jonas',
18 age: 30,
19};
20const friend = me;
21friend.age = 27;
22console.log(friend.age); // 27
23console.log(me.age); // 30
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}