Created
June 6, 2019 17:36
-
-
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.
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; | |
| }; | |
| // 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