constx=[]x.push(x)cloneObject(x)// Uncaught RangeError: Maximum call stack size exceeded
To avoid that, you'll need to store references, for which a Map is easily the best possible option, but you need to make sure you fill the map with a reference/clone pair before you start the recursion:
Yes and no. JSON.parse/stringify will serialize and deserialize the data. Some types are not supported and cyclic references will also lead to errors. But putting both variants together, you'll get:
I guess libraries like lodash made it convenient enough to have that functionality, so there was no reason to provide a native method. Also, since the native types are currently a moving target, it seems prudent to wait until it has stabilized enough to make such a functionality feasible. That shouldn't stop anybody from making your own proposal to the TC39 committee to include Object.clone(obj) into a future ECMAScript standard, though.
If you want to do it yourself for simple cases, you can just use recursion:
But beware of cyclic references, i.e.
To avoid that, you'll need to store references, for which a Map is easily the best possible option, but you need to make sure you fill the map with a reference/clone pair before you start the recursion:
Now cyclic references are no longer an issue:
That still doesn't handle stuff like constructed objects, though (Date, Headers, etc.).
Hey, that basically will do the same as the JSON method right?
This is one way to sort of deep-clone, haven't tested this fully:
Response:
Yes and no. JSON.parse/stringify will serialize and deserialize the data. Some types are not supported and cyclic references will also lead to errors. But putting both variants together, you'll get:
Now that works for all usual types. It will fail for some of the modern things like Map/WeakMap etc.
It all goes deeper than you would think, wonder why they don't build this in ECMAScript...
Seems like a pretty "basic" function to deepclone right?
I guess libraries like lodash made it convenient enough to have that functionality, so there was no reason to provide a native method. Also, since the native types are currently a moving target, it seems prudent to wait until it has stabilized enough to make such a functionality feasible. That shouldn't stop anybody from making your own proposal to the TC39 committee to include
Object.clone(obj)
into a future ECMAScript standard, though.I guess I'll make a proposal myself, if nobody beats me to it. Here's the polyfill:
I also did a small test suite and a documentation. I'll work a bit on it and then release it to the public.
Wow Alex, Your a speedy guy!
Nice work, happy to test with you 👀
Here's the initial draft: github.com/atk/object-clone-proposal. Feedback is appreciated.