Created
December 2, 2012 22:55
-
-
Save Ely-S/4191458 to your computer and use it in GitHub Desktop.
Fastest way to Deep Clone/Extend an object in javascript
This file contains 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
//benchmark available here | |
// clone is the object to recursively copy the attributes of obj to overwriting as necessary. | |
function x(clone, obj) { | |
for(var i in obj) | |
clone[i] = (typeof obj[i] == "object") ? x(obj[i].constructor(), obj[i]) : obj[i]; | |
return clone; | |
} |
(typeof obj[i] == "object")
should be
(typeof obj[i] == "object" && obj[i] !== null)
or even (obj[i] && typeof obj[i] == "object")
this ends up being 3 times faster than JSON.parse(JSON.stringify(obj))
and is barely more code 😍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks guy, I haven't found a faster way to clone objects than yours 👍