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 y = Object.assign({}, x);
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.
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));
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