Last active
March 31, 2018 10:53
-
-
Save Hamzali/e326eed7ca9c5d4659a1a189168a7005 to your computer and use it in GitHub Desktop.
Object Deep Clone, It might hurt! Beware
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
// Create a big object in this and test the methods and see the results. | |
// I could not find a good way to deep clone an object. | |
const o = { | |
}; | |
// declarative version with Object assign | |
// Never use this on big objects! | |
const deepCloneV1 = o => Object.assign({}, o, Object | |
.keys(o) | |
.filter(k => o[k] && typeof o[k] === 'object') | |
.reduce((acc, k) => { | |
if (Array.isArray(o[k])) { | |
acc[k] = [...o[k]]; | |
return acc; | |
} | |
acc[k] = deepCloneV1(o[k]); | |
return acc; | |
}, {})); | |
// imperative plain version | |
// Never use this on big objects! | |
function deepCloneV2 (o) { | |
const newO = {}; | |
const keys = Object.keys(o); | |
for (let k, i = 0; i < keys.length; i++) { | |
k = keys[i]; | |
if(Array.isArray(o[k])) { | |
newO[k] = [...o[k]] | |
} else if (o[k] && typeof o[k] === 'object') { | |
newO[k] = deepCloneV2(o[k]); | |
} else { | |
newO[k] = o[k]; | |
} | |
} | |
return newO; | |
} | |
// Plain old stringify method | |
// Never use this on big objects! | |
// but best option | |
const deepCloneV3 = o => JSON.parse(JSON.stringify(o)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment