Skip to content

Instantly share code, notes, and snippets.

@shepelevstas
Last active August 20, 2022 23:01
Show Gist options
  • Save shepelevstas/6350b42995514ef28fa4e2e8262cbcad to your computer and use it in GitHub Desktop.
Save shepelevstas/6350b42995514ef28fa4e2e8262cbcad to your computer and use it in GitHub Desktop.
deep copy js
// correct object cloning
function clone(obj, fields) {
if (null == obj || "object" != typeof obj) return obj;
if (obj.constructor == File && obj.size)
return obj
var copy = obj.constructor();
if (fields){
for (let i of fields)
if (obj.hasOwnProperty(i))
copy[i] = clone(obj[i])
} else {
for (let attr in obj)
if (obj.hasOwnProperty(attr))
copy[attr] = clone(obj[attr]);
}
return copy;
}
const deep_copy = (obj, keys=null) => {
if (obj===null || typeof(obj) !== 'object') {return obj}
if (obj.constructor == File && obj.size) {return obj}
const copy = obj.constructor()
keys = keys || Object.keys(obj)
for (let k of keys)
if (obj.hasOwnProperty(k))
copy[k] = deep_copy(obj[k], keys)
return copy
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment