Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Last active April 15, 2019 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladchinda/75355e7f7992e800b5350c8c992df9b0 to your computer and use it in GitHub Desktop.
Save gladchinda/75355e7f7992e800b5350c8c992df9b0 to your computer and use it in GitHub Desktop.
/**
* Returns a deep copy of the array or object passed to it.
* Useful for copying objects and arrays with nested complex types.
*
* @param {array|object} o The value to deep copy, could be array or object.
* @returns {array|object} Returns a deep copy of the supplied array or object.
*/
function deepClone(o) {
// Construct the copy `output` array or object.
// Use `Array.isArray()` to check if `o` is an array.
// If `o` is an array, set the copy `output` to an empty array (`[]`).
// Otherwise, set the copy `output` to an empty object (`{}`).
//
// If `Array.isArray()` is not supported, this can be used as an alternative:
// Object.prototype.toString.call(o) === '[object Array]'
// However, it is a fragile alternative.
const output = Array.isArray(o) ? [] : {};
// Loop through all the properties of `o`
for (let i in o) {
// Get the value of the current property of `o`
const value = o[i];
// If the value of the current property is an object and is not null,
// deep clone the value and assign it to the same property on the copy `output`.
// Otherwise, assign the raw value to the property on the copy `output`.
output[i] = value !== null && typeof value === 'object' ? deepClone(value) : value;
}
// Return the copy `output`.
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment