Skip to content

Commit a32a5a5

Browse files
Deep copy and shallow copy object
1 parent 600d210 commit a32a5a5

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

interview1.js

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,6 @@ user2.age = 65;
3131
console.log(user2); // { name: "Rahul Kumar", age: 65 }
3232
console.log(prevUser2); // { name: "Rahul Kumar", age: 24 }
3333

34-
35-
3634
// Deep Copy and Shallow Copy in javaScript
3735
// [Value of objects can be changed by two mwthods : (refrence and By Value)]
3836
let obj = {
@@ -54,12 +52,7 @@ let user = obj; // {Here we assign obj Object to user Object
5452
console.log(name) // sunil]
5553
*/
5654

57-
58-
59-
60-
61-
62-
// Shallow Copy
55+
// Shallow Copy [It is for one level of object]
6356
let obj1 = {
6457
name: "Shyam",
6558
};
@@ -76,4 +69,24 @@ const ans1 = Object.assign({}, obj1);
7669
ans1.name = "Sudhir";
7770
console.log(ans1); //{ name: 'Sudhir' }
7871

79-
console.log(obj1);//{ name: 'Shyam' }
72+
console.log(obj1); //{ name: 'Shyam' }
73+
74+
// Deep Copy [It is for Nested object]
75+
76+
let userObj = {
77+
name: "Sunil",
78+
age: 98,
79+
address: {
80+
city: "Patna",
81+
pin: 456756,
82+
state: "Bihar",
83+
},
84+
};
85+
86+
const res = JSON.stringify(userObj);
87+
const res1 = JSON.parse(res);
88+
89+
res1.address.pin = 800006;
90+
console.log(res1); //{name: 'Sunil',age: 98,address: { city: 'Patna', pin: 800006, state: 'Bihar' }}
91+
92+
console.log(userObj); //{name: 'Sunil',age: 98,address: { city: 'Patna', pin: 456756, state: 'Bihar' }}

0 commit comments

Comments
 (0)