deepClone
Creates a deep clone of an object. Clones primitives, arrays and objects, excluding class instances.
- Use recursion.
- Check if the passed object is
nulland, if so, returnnull. - Use
Object.assign()and an empty object ({}) to create a shallow clone of the original. - Use
Object.keys()andArray.prototype.forEach()to determine which key-value pairs need to be deep cloned. - If the object is an
Array, set theclone'slengthto that of the original and useArray.from(clone)to create a clone.
const deepClone = obj => {
if (obj === null) return null;
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key =>
(clone[key] =
typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
if (Array.isArray(obj)) {
clone.length = obj.length;
return Array.from(clone);
}
return clone;
};