The Best Way to Deep Clone an Object in JavaScript (See my blog post: https://www.workingsoftware.dev/how-to-deep-clone-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
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