Skip to content

Instantly share code, notes, and snippets.

@Hamzali
Last active March 31, 2018 10:53
Show Gist options
  • Save Hamzali/e326eed7ca9c5d4659a1a189168a7005 to your computer and use it in GitHub Desktop.
Save Hamzali/e326eed7ca9c5d4659a1a189168a7005 to your computer and use it in GitHub Desktop.
Object Deep Clone, It might hurt! Beware
// 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