Skip to content

Instantly share code, notes, and snippets.

@MatthewYee92
Created June 6, 2019 17:36
Show Gist options
  • Select an option

  • Save MatthewYee92/2b17c26db4fcaacc4b86429940f71876 to your computer and use it in GitHub Desktop.

Select an option

Save MatthewYee92/2b17c26db4fcaacc4b86429940f71876 to your computer and use it in GitHub Desktop.
Creates a deep clone of an object. Use recursion. Use Object.assign() and an empty object ({}) to create a shallow clone of the original. Use Object.keys() and Array.prototype.forEach() to determine which key-value pairs need to be deep cloned.
const deepClone = obj => {
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
return Array.isArray(obj) && obj.length
? (clone.length = obj.length) && Array.from(clone)
: Array.isArray(obj)
? Array.from(obj)
: clone;
};
// Examples :
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment