Last active
September 21, 2022 17:19
-
-
Save 0bie/51bcfccc017336d3efadf10f22c21c8b to your computer and use it in GitHub Desktop.
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
/** | |
* check if vals are objects | |
* if so. copy that object (deep copy) | |
* else return the value | |
*/ | |
function deepCopy(obj) { | |
const keys = Object.keys(obj); | |
const newObject = {}; | |
for (let i = 0; i < keys.length; i++) { | |
const key = keys[i]; | |
if (typeof obj[key] === 'object') { | |
newObject[key] = deepCopy(obj[key]); | |
} else { | |
newObject[key] = obj[key]; | |
} | |
} | |
return newObject; | |
} | |
const x = {a: 1, b: 2, c: {a: 1}}; | |
const y = deepCopy(x); | |
y.c.b = 2; | |
console.log('x:', x); | |
console.log('y:', y); | |
// https://medium.com/@tkssharma/objects-in-javascript-object-assign-deep-copy-64106c9aefab |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment