Created
October 26, 2020 11:42
-
-
Save ross-u/afe5f55656b52cea5e809ee4a2a1a3a1 to your computer and use it in GitHub Desktop.
Deep copying custom function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cloneObject(object) { | |
let copy; | |
if (Array.isArray(object)) { | |
copy = []; | |
} else { | |
copy = {}; | |
} | |
for(let key in object) { | |
if(typeof(object[key]) === "object" && object[key] !== null ){ | |
copy[key] = cloneObject(object[key]); | |
} else { | |
copy[key] = object[key]; | |
} | |
} | |
return copy; | |
} | |
let original = { | |
name: 'Sarah', | |
age: 35, | |
family: [ | |
{ name: 'Mark', age: 29 }, | |
{ name: 'Linda', age: 33 } | |
] | |
} | |
let clonedObject = cloneObject(original); | |
console.log(original); | |
console.log(clonedObject); | |
// each object has distinct reference | |
console.log('original === clonedObject', original === clonedObject); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment