Which is the best method for deep cloning in JavaScript?
1–10 of 62 posts
Re: Which is the best method for deep cloning in JavaScript?
#2Similarly, cloning things like getters means you're potentially copying over closures, which means your new cloned object now has references to its source and interacting with it may mutate the source. This is a pretty serious hazard that (IMO) justifies not cloning getters/setters, at least by default.
Cloning freeze/seal status would also lower the usability of your cloning API, because now if you wanted to make a non-frozen copy of a frozen object, you can't use the clone API.
Re: Which is the best method for deep cloning in JavaScript?
#3Re: Which is the best method for deep cloning in JavaScript?
#4I only clone data using JSON.parse(JSON.stringify(someThing)), and thus avoid all the mess that comes with trying to clone anything else than primitives types.
Re: Which is the best method for deep cloning in JavaScript?
#5A lot of the problems described in this (very detailed, nice work!) comparison are not really problems so much as design decisions. Having a clone operation that copies non-enumerable properties is, depending on what you're doing, a bad thing. They're not enumerable for a reason. Similarly, cloning things like getters means you're potentially copying over closures, which means your new cloned object now has reference…
There is a reason none of the libraries tested got it "right" - nobody needs it. Or if they do, they just write their own implementation.
Re: Which is the best method for deep cloning in JavaScript?
#6I only clone data using JSON.parse(JSON.stringify(someThing)), and thus avoid all the mess that comes with trying to clone anything else than primitives types.
I sure hope `someThing` is never `undefined`, for your sake.
Re: Which is the best method for deep cloning in JavaScript?
#7Re: Which is the best method for deep cloning in JavaScript?
#8But one thing not included in this page is that there are things it just doesn't serialize, even when it's actual data:
const native = { number: Number.POSITIVE_INFINITY };
const cloned = JSON.parse(JSON.stringify(native));
// unlike NaN, we can compare Number.POSITIVE_INFINITY to itself
console.log(native.number === native.number);
// but it doesn't serialize
console.log(native.number === cloned.number);
console.log(cloned);
Yields true
false
{number: null}
Oops.Re: Which is the best method for deep cloning in JavaScript?
#9Re: Which is the best method for deep cloning in JavaScript?
#10I only clone data using JSON.parse(JSON.stringify(someThing)), and thus avoid all the mess that comes with trying to clone anything else than primitives types.
"cloneJSON is very slow and can’t do much. Please avoid it."
I mean, I also use it since forever.
But I might look into the winner cloneLib.
If it is really faster, it might be worth it, but I likely still won't trust it for anything complex.