Created
February 23, 2022 23:13
-
-
Save Alonso-Pablo/4a161022546f8369d0e358660489f527 to your computer and use it in GitHub Desktop.
Clone a object in JavaScript
This file contains 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 deepCopy(subject) { | |
let copySubject; | |
const subjectIsObject = isObject(subject); | |
const subjectIsArray = isArray(subject); | |
if (subjectIsArray) { | |
copySubject = []; | |
} else if (subjectIsObject) { | |
copySubject = {}; | |
} else { | |
return subject; | |
} | |
for (key in subject) { | |
const keyIsObject = isObject(subject[key]); | |
if (keyIsObject) { | |
copySubject[key] = deepCopy(subject[key]); | |
} else { | |
if (subjectIsArray) { | |
copySubject.push(subject[key]); | |
} else { | |
copySubject[key] = subject[key]; | |
} | |
} | |
} | |
return copySubject; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment