-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcopy-by-value.js
93 lines (67 loc) · 1.89 KB
/
copy-by-value.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
let obj = {
fullName: {
firstName: "Vanshu",
lastName: "Hassija",
},
address: {
city: "Patiala",
state: "Punjab",
},
age: 24,
};
let objCopy=obj;
// objCopy.age=25;
//If You change in copy the change is reflected in The Original Object
//In Javascript Objects are copied by reference and not by value
//When I want to copy by value
//How To Copy By Value
//1. Object.create
// number--> Number
// strings ---> String
// boolean ---> Boolean
// objects ---> Object
const objCopyByValue1=Object.create(obj);
objCopyByValue1.age=26;
console.log("Obj age",obj.age);
console.log("ObjCopy Age",objCopyByValue1.age);
//Object.create creates a shallow copy
// objCopyByValue1.address.city="Ludhiana"
console.log("Obj age",obj.address.city);
console.log("ObjCopy Age",objCopyByValue1.address.city);
//Shallow Copy Means Copying by Value only for the properties at level 1
//It does not copy by value for nested objects
//2. JSON.stringify,JSON.parse
//Convert the Object To String
//JSON.stringify()
//JSON: Javascript Object Notation
const deepCopy=JSON.parse(JSON.stringify(obj));
deepCopy.address.city="Ludhiana"
console.log("Obj age",obj.address.city);
console.log("ObjCopy Age",deepCopy.address.city);
//Convert The String to Object Again
//JSON.parse()
//It creates a deep Copy
//3. Spread Operator
//I can spread Arrays and Objects
//...
//Create an object
const spreadObject={...obj};
//Shallow Copy of obj Object
console.log("SpreadObject is",spreadObject);
spreadObject.age=28;
console.log(obj.age,spreadObject.age,"Age")
spreadObject.address.city="Amritsar";
console.log(obj.address.city,spreadObject.address.city,"Age")
const obj2={
name:"Vanshu",
city:"Patiala",
state:"Punjab"
}
const obj3={
name:"Rajat",
age:22,
state:"Uttar Pradesh",
subject:"Mathematics"
}
const combinedObj={...obj3,...obj2};
console.log("Combined Object",combinedObj);