Skip to content

Instantly share code, notes, and snippets.

@benergize
Created December 10, 2020 15:16
Show Gist options
  • Save benergize/255fcaa4db1b65aa15db4a56bf5a9dfb to your computer and use it in GitHub Desktop.
Save benergize/255fcaa4db1b65aa15db4a56bf5a9dfb to your computer and use it in GitHub Desktop.
Recursively copies a JS object without drawing any references.
function Instance(obj) {
let nobj={};
for(let prop in obj) {
let val = obj[prop];
if(typeof val === "number") { nobj[prop] = Number(val); }
if(typeof val === "string") { nobj[prop] = String(val); }
if(typeof val === "function") { nobj[prop] = val; }
if(typeof val === "object") {
if(Array.isArray(val)) {
nobj[prop]=[];
for(let i = 0; i < val.length; i++) {
nobj[prop][i] = Instance(val[i]);
}
}
else {
nobj[prop] = Instance(val);
}
}
}
return nobj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment