Last active
August 20, 2022 23:01
-
-
Save shepelevstas/6350b42995514ef28fa4e2e8262cbcad to your computer and use it in GitHub Desktop.
deep copy js
This file contains hidden or 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
// 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