Skip to content

Instantly share code, notes, and snippets.

@Alonso-Pablo
Created February 23, 2022 23:13
Show Gist options
  • Save Alonso-Pablo/4a161022546f8369d0e358660489f527 to your computer and use it in GitHub Desktop.
Save Alonso-Pablo/4a161022546f8369d0e358660489f527 to your computer and use it in GitHub Desktop.
Clone a object in JavaScript
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