-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsection5.js
49 lines (39 loc) · 1.07 KB
/
section5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//TODO Mutations
// How to avoid mutation of the object
// 1st method
const Chinese = {
HongKong: "Cantonese",
Taiwan: "Mandarin",
Shanghai: "Shanghainese",
};
const ChineseCopy = Object.assign({}, Chinese); // copy without mutation. "{}" is an empty object
ChineseCopy.HongKong = "Mandarin";
console.log(Chinese);
console.log(ChineseCopy);
// But this method is not recommended, because it doesn't work with nested objects.
// 2nd method
const Music = {
pop: "The Weeknd",
phonk: "Fluxxwave",
rap: "Eminem",
};
const MusicCopy = { ...Music }; // "..." is a spread operator.
MusicCopy.pop = "Drake";
console.log(Music);
console.log(MusicCopy);
// This method doesn't work with nested objects neither.
// 3rd method
const book = {
British: "Joan Rowling",
Japanese: "Haruki Murakami",
Chinese: "Mo Yan",
Korean: {
name: "Han Kang",
book: "The Vegetarian",
},
};
const bookCopy = JSON.parse(JSON.stringify(book)); // copy without mutation at all
bookCopy.Korean.name = "warrior";
bookCopy.British = "Stephen King";
console.log(book);
console.log(bookCopy);