guy, i try to write a deepcopy function but it cant not work , but i cant not figure out the problem .
below is my script
<script>
const obj = {
name : 'ABC',
age : 18,
habbit : ['baseball', 'football', ['genshin', 'princess']],
family : {
son : 'sp',
father:'fa'
}
}
const newObj = {}
function deepCopy(obj, newObj){
for(k in obj){
if(obj[k] instanceof Array){
const arr = []
deepCopy(obj[k], arr)
newObj[k] = arr
}else if(obj[k] instanceof Object){
const oo = {}
deepCopy(obj[k], oo)
newObj[k] = oo
}else{
newObj[k] = obj[k]
}
}
}
deepCopy(obj,newObj)
console.log(newObj)
</script>
and the reult is
enter image description here
habbit and family is wrong
i dnot know why im sorry. logic is stock
2
Answers
I think you can use
to clone Object and its nested Array/Object
do it like that easily