Created
July 26, 2019 15:34
-
-
Save RinatValiullov/0eb83419ff1a2baf9f059c5885ad3646 to your computer and use it in GitHub Desktop.
Creates a deep clone of an object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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