Skip to content

Instantly share code, notes, and snippets.

@bitsmuggler
Last active January 16, 2023 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitsmuggler/deda06939a01ba8fab6209a44ff9fcdb to your computer and use it in GitHub Desktop.
Save bitsmuggler/deda06939a01ba8fab6209a44ff9fcdb to your computer and use it in GitHub Desktop.
The Best Way to Deep Clone an Object in JavaScript (See my blog post: https://www.workingsoftware.dev/how-to-deep-clone-in-javascript/)
import { strict as assert } from 'assert';
//
// Deep Clone of an object
// Blog-Post: https://www.workingsoftware.dev/how-to-deep-clone-in-javascript/
//
// Self-Made
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
let clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
const myExampleObject = {
name: 'Max',
age: 30,
hobbies: ['Sports', 'Cooking'],
address: {
street: 'Mainstreet 1',
city: 'Berlin',
},
};
const myExampleDeepClone = deepClone(myExampleObject);
const myExampleStructuredClone = structuredClone(myExampleObject);
const myExampleJsonParse = JSON.parse(JSON.stringify(myExampleObject));
const myExampleAssign = Object.assign({}, myExampleObject); // shallow copy !
const myExampleSpreadSyntax = { ...myExampleObject }; // shallow copy !
// Deep clone
assert.equal(myExampleDeepClone === myExampleObject, false);
assert.equal(myExampleDeepClone.address === myExampleObject.address, false);
assert.equal(myExampleStructuredClone === myExampleObject, false);
assert.equal(
myExampleStructuredClone.address === myExampleObject.address,
false
);
assert.equal(myExampleJsonParse === myExampleObject, false);
assert.equal(myExampleJsonParse.address === myExampleObject.address, false);
// Referenzen werden kopiert (shallow copy)
assert.equal(myExampleSpreadSyntax === myExampleObject, false);
assert.equal(myExampleSpreadSyntax.address === myExampleObject.address, true); // (!)
assert.equal(myExampleAssign === myExampleObject, false);
assert.equal(myExampleAssign.address === myExampleObject.address, true); // (!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment