Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
port2211059yThere's multiple ways to do it but that's the most efficient way to do a deep copy. Keep in mind that this won't keep functions and won't convert date objects back from string format.
-
afduarte5999y@bluefirex I was actually, for that project, but I'm sure there must be a better way...
-
port2211059y@afduarte it depends upon your needs. The most efficient way if you know the structure of the object is to do a manual construction of the cloned object, this won't be a 1 line solution but it's the most efficient. For a 1 line solution, or one where you don't know the object structure you can use extend, or the string parsing. If you're doing a shallow copy, use extend. For a deep copy, stringify/parse is more efficient than extend but has a few limitations.
-
afduarte5999y@PermeableTub For most of the time, I don't, but that was quite a small project for a class and I didn't want to use angular because I'm not familiar enough with it to spin it up as fast as something like Vanilla JS with JQuery
-
I'm pretty sure looping through the properties, and assigning the to the new object would give you a shallow copy without reference. Would take some tweaking for a deep copy though
-
lodash has a deep clone function which handles all the tricky corner cases. It's an expensive operation, though I find it hard to imagine it's more expensive than serializing and then parsing. If performance is critical you should probably write your own special purpose clone function which makes use of your knowledge about the structure of the object.
Related Rants
Please someone tell me there's a better way to copy an object in Javascript...
I can't live with a language where I have to do this
undefined
js
whatthehell
oop