4 ms·
I've been programming JS for a very long time and have learned to just stop trying to do a generic deep copy. Since JS is a dynamically typed language, it will
by mrgalaxy 8y ago
I've been programming JS for a very long time and have learned to just stop trying to do a generic deep copy. Since JS is a dynamically typed language, it will always lead to issues down the road. Instead I write domain specific merge methods for whatever objects I'm merging.
function mergeOptions(...options) {
const result = {};
for (const opt of options) {
result = {
...result,
...opt
arrayValue: [
...(result.arrayValue || []),
...(opt.arrayValue || [])
],
deepObject: {
...result.deepObject,
...opt.deepObject
}
};
}
return result;
}
Know the shape of your objects and merging deeply becomes painless and won't have edge-cases.
- ben509 8y agoAnother way of looking at it: if you are frequently doing complex copies, you probably want immutable types.
- throwaway645738 8y agoIm away from my usual PCs, and Im here just to say when I realized this exact same thing it all clicked for me on why to use immutable objects
- deleted 8y ago[deleted]
- cageface 8y agoImmerjs is a very handy library for doing this kind of thing. It is a natural fit for react but can be used for any kind of copying like this.
- 0xFACEFEED 8y ago+1 for immer. I love it. If anyone here ends up using it, make sure you learn how it works first. There are performance implications. It may not matter but it's important to know what they are. Also it's generally best practice to learn how magical utilities like immer do what they do before using them!
- lxe 8y agoI think it's not the best idea to keeping the shapes of objects in your head and manually cloning/merging them. This will lead to bugs, as inadvertently as a human you'll miss a merge or a clone and retain references that you don't want. Inability of a language or runtime to correctly and quickly clone a structure is an upsetting fact of JavaScript.