Created
September 4, 2019 03:06
-
-
Save shekhardtu/28247be45237a592cdfd7e858b92372d to your computer and use it in GitHub Desktop.
deepClone implementation of object in javascript
This file contains 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; | |
}; | |
// Example | |
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