Skip to content

Instantly share code, notes, and snippets.

@IamManchanda
Last active June 9, 2018 23:07
Show Gist options
  • Save IamManchanda/43fb4d8b9e744bab0919e455ed9b9a7a to your computer and use it in GitHub Desktop.
Save IamManchanda/43fb4d8b9e744bab0919e455ed9b9a7a to your computer and use it in GitHub Desktop.
Deep Copy By Value
const deepCopy = (value) => { // deepCopy by Value
let val;
if (Array.isArray(value)) {
val = [...value]; // Copy by Value
} else if (value && typeof value === 'object') {
val = { ...value }; // Copy by Value
} else {
return value; // Returns original value and stops!
}
Object.keys(val).forEach((key) => {
if (val[key]) {
if (Array.isArray(val[key]) || (typeof val[key] === 'object')) {
val[key] = deepCopy(val[key]); // Recursion
}
}
});
return val;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment