Skip to content

Instantly share code, notes, and snippets.

@Ely-S
Created December 2, 2012 22:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ely-S/4191458 to your computer and use it in GitHub Desktop.
Save Ely-S/4191458 to your computer and use it in GitHub Desktop.
Fastest way to Deep Clone/Extend an object in javascript
//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;
}
@ClementNerma
Copy link

ClementNerma commented Feb 13, 2017

Thanks guy, I haven't found a faster way to clone objects than yours 👍

@ipsips
Copy link

ipsips commented Mar 1, 2017

(typeof obj[i] == "object")
should be
(typeof obj[i] == "object" && obj[i] !== null)

@tbjgolden
Copy link

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