0

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

LOSHI
  • 1
  • 2
  • 1
    see: [structuredClone()](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) – pilchard May 07 '23 at 16:16
  • The problem in your code is `for(k in obj){`. This declares a global variable that is mutated in the recursive calls. Use `for(const k in obj){` to fix your code. Always use strict mode to avoid such problems. – jabaa May 07 '23 at 22:28

2 Answers2

-3

do it like that easily

const obj = {
        name : 'ABC',
        age : 18,
        habbit : ['baseball', 'football', ['genshin', 'princess']],
        family : {
            son : 'sp',
            father:'fa'
        }
    }
  const copy =Object.assign({}, obj);
paliz
  • 347
  • 2
  • 5
-4

I think you can use

const copy = JSON.parse(JSON.stringify(original));

to clone Object and its nested Array/Object

AdvMaple
  • 99
  • 1
  • 7