Search This Blog

2026/08/07

deep copy nested object

  Write a code to deep copy nested object.

Code:
var obj ={
    name:"sangram",
    address:{
        city:"mumbai",
        state:"maharashtra",
        pin:"4000**",
office:null,
        contactNo:{
            "landline":"***67-554569",
            "mobile":"**78456729",
        }
    }
}

function deepCopy(obj){
    var deepCopied={}
    for(let key in obj){
        if (obj[key] !== null || typeof obj[key] !== "object") {
            deepCopied[key] = obj[key]
        }else{
            deepCopied[key] = deepCopy(obj[key])
        }
    }
    return deepCopied
}

let x = deepCopy(obj);
console.log("Final Output:",x)

Output:

Final Output: {
  name: 'sangram',
  address: {
    city: 'mumbai',
    state: 'maharashtra',
    pin: '4000**',
office:null,
    contactNo: { landline: '***67-554569', mobile: '**78456729' }
  }
}

Note:deepcopy & deepclone term are used interchangeably in interviews & discussion.

No comments:

Post a Comment