skip to Main Content

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


  1. I think you can use

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

    to clone Object and its nested Array/Object

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search