Skip to content

Instantly share code, notes, and snippets.

@RinatValiullov
Created July 26, 2019 15:34
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 RinatValiullov/0eb83419ff1a2baf9f059c5885ad3646 to your computer and use it in GitHub Desktop.
Save RinatValiullov/0eb83419ff1a2baf9f059c5885ad3646 to your computer and use it in GitHub Desktop.
Creates a deep clone of an object.
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;
};
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