Skip to content

Commit 34ae88f

Browse files
authored
Merge pull request sadanandpai#38 from ptbhatcoder/patch-2
Add a way to deep copy an object recursively
2 parents 5690f83 + 7470749 commit 34ae88f

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

challenges/objects-challenges.md

+19
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,25 @@ const x = { ...obj};
9090
const x = JSON.parse(JSON.stringify(obj));
9191
```
9292

93+
```js
94+
function deepCopy(obj){
95+
if(!obj) return obj;
96+
const copyObj = {};
97+
for(const key in obj){
98+
let val;
99+
if(typeof obj[key] !== 'object')
100+
val = obj[key];
101+
else
102+
val = deepCopy(obj[key]);
103+
104+
copyObj[key] = val;
105+
}
106+
return copyObj;
107+
}
108+
109+
const x = deepCopy(obj);
110+
```
111+
93112
###### Notes
94113
3rd solution provided does deep copy of a nested object also but this technique results in loss of data
95114

0 commit comments

Comments
 (0)