Last active
February 7, 2018 14:09
-
-
Save Loupax/87bf92e38c32cac197448f23cba4e110 to your computer and use it in GitHub Desktop.
Deep cloning functionality for 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
function cloneObject(input) { | |
if (isPrimitive(input)) { | |
return input; | |
} | |
if (Array.isArray(input)) { | |
return input.map((item)=>{return cloneObject(item);}); | |
} | |
const clone = {}; | |
for (let prop in input) { | |
if (input[prop] instanceof Date) { | |
clone[prop] = new Date(input[prop].getTime()); | |
} else if(Array.isArray(input[prop])) { | |
clone[prop] = input[prop].map((item)=>{return cloneObject(item);}); | |
} else if (input[prop] != null && typeof(input[prop]) == "object") { | |
clone[prop] = cloneObject(input[prop]); | |
} else { | |
clone[prop] = input[prop]; | |
} | |
} | |
return clone; | |
} | |
function isPrimitive(test) { | |
return (test !== Object(test)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment