-
Notifications
You must be signed in to change notification settings - Fork 1
/
shallow_deep_copy.html
68 lines (56 loc) · 1.63 KB
/
shallow_deep_copy.html
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html>
<head>
<title>Shallow copy Vs Deep copy in Javascript</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
</head>
<body>
<h2>Shallow copy Vs Deep copy in Javascript</h2>
<script>
/*
Example of Shallow copy
*/
const animals_shallow = {
category: 'domestic',
name: {
animal : 'Cow'
}
};
// copy object using Object.assign
let printAnimal = Object.assign({}, animals_shallow);
console.log(printAnimal);
printAnimal.category = 'wild';
console.log(printAnimal.category);
console.log(animals_shallow.category);
printAnimal.name.animal = 'Dog';
console.log(printAnimal.name.animal);
console.log(animals_shallow.name.animal);
// copy object using spread operator
const animals = {
category: 'domestic',
name: {
animal : 'Cow'
}
};
let printAnimal_spread = {...animals};
console.log(printAnimal_spread);
printAnimal_spread.name.animal = 'Goat';
console.log(printAnimal_spread.name.animal);
console.log(animals.name.animal);
console.log(animals);
// Deep copy using Lodash
const animals_lodash = {
category: 'wild',
name: {
animal : 'Tiger'
}
};
let cloneAnimals = _.cloneDeep(animals_lodash);
cloneAnimals.name.animal = 'Lion';
console.log(cloneAnimals.name.animal);
console.log('Current Object => ', cloneAnimals);
console.log(animals_lodash.name.animal);
console.log('Original Object => ', animals_lodash);
</script>
</body>
</html>