Skip to content

Instantly share code, notes, and snippets.

@0bie
Last active September 21, 2022 17:19
Show Gist options
  • Save 0bie/51bcfccc017336d3efadf10f22c21c8b to your computer and use it in GitHub Desktop.
Save 0bie/51bcfccc017336d3efadf10f22c21c8b to your computer and use it in GitHub Desktop.
/**
* 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