Skip to content

Commit 69076e9

Browse files
feat: add deep clone
1 parent e8be8ae commit 69076e9

File tree

1 file changed

+26
-26
lines changed

1 file changed

+26
-26
lines changed

part4 (Arrays and Loops)/04_deepCopy_shallowCopy.js

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,26 @@ console.log(myFruits.push("Dates"));
99
console.log(fruits);
1010
console.log(myFruits);
1111

12-
1312
const user1 = {
14-
firstName: "Abdul",
15-
lastName: "rafay"
13+
firstName: "Abdul",
14+
lastName: "rafay",
1615
};
1716
const user2 = user1;
1817

1918
user2.firstName = "whoami";
2019
console.log(user2);
2120
console.log(user1);
2221

23-
2422
const username1 = "abdul rafay";
2523
let username2 = username1;
26-
username2 += " " + "whoami"
24+
username2 += " " + "whoami";
2725

2826
console.log(username1);
2927
console.log(username2);
3028

3129
const obj = {
32-
name: "whoami",
33-
age: 17
30+
name: "whoami",
31+
age: 17,
3432
};
3533
const obj2 = { ...obj };
3634
obj2.name = "nobody";
@@ -43,7 +41,6 @@ obj3.age = 18;
4341
console.log(obj);
4442
console.log(obj3);
4543

46-
4744
const arr = ["whoami", "zain", "rafay"];
4845

4946
const arr1 = [...arr];
@@ -60,29 +57,32 @@ console.log(arr1);
6057
console.log(arr2);
6158
console.log(arr3);
6259

63-
6460
// FIXME: How to do a Deep Copy
6561
// INFO: There are two ways that i will gonna show you to do a deep copy
6662
const object1 = {
67-
name: "rafay",
68-
age: 25,
69-
social: {
70-
facebook: {
71-
72-
73-
},
74-
twitter: {
75-
free: {
76-
77-
},
78-
paid: {
79-
80-
}
81-
}
82-
}
83-
}
63+
name: "rafay",
64+
age: 25,
65+
social: {
66+
facebook: {
67+
68+
69+
},
70+
twitter: {
71+
free: {
72+
73+
},
74+
paid: {
75+
76+
},
77+
},
78+
},
79+
};
8480

8581
const object2 = JSON.parse(JSON.stringify(object1));
8682
object2.social.facebook.ac1 = "changed";
8783
console.log(object1.social.facebook.ac1);
8884
console.log(object2.social.facebook.ac1);
85+
86+
// Second method
87+
const clone = structuredClone(object1);
88+
console.log(clone);

0 commit comments

Comments
 (0)