Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement