Scenario:
Whenever we pass objects between components as props or as arguments in function, we need to copy that object to make sure tha...
For further actions, you may consider blocking this person and/or reporting abuse
There is a cool library available for cloning objects efficiently called rfdc (Really Fast Deep Clone).
The great thing about rfdc is that it super quickly clones real objects with cycles/functions/constructors etc. It is super quick at that.
If you need to quick clone something including enumerable properties but NOT any of that cool stuff rfdc does - then I use this that is a little quicker if you know that there won't be issues:
Thanks, Mike for sharing this.
looks good 👍🏻
Thanks for sharing!
Thanks for such a cool suggestion.
Infact after your comment, I have looked into it and its comparision with other libraries. I think it's very efficient.
👍🏻
Great article. Many of us encounter this problem and don't know how to resolve it. I've personally encountered it once or twice.
So there is a lodash library which gives cloneDeep() method to perfectly deep copy an object. Below an example attached:
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
You can also visit this page to find more: lodash.com/docs/4.17.15#cloneDeep
Another approach is to use recursion.
make a custom function like one I have used to iterate on each key in object and if that key is also an object then again call the method to copy the keys.
Something like below:
I surely will use the recursion approach too. However,
typeof
is sloppy in terms of differentiating between array and object. In order to truly check forobject
type, I will go with plain old trick below:Cool. I missed that part. Thanks for the solution.
I was just giving some information about how can we make such a function to deep copying with help of recursion. So, there might be some more improvements that can be implemented to make it handle every case.
But Great Insight!
That's a good point.
I have stopped using lodash. I will use the recursive function
I like the recursive function.
Great! make your own common function to handle all cases.
Enjoy!
Great article!
Just last week i encountered this same issue with some production code:
we had a video player that accepts some options when you initialize it; for some strange reasons if 2 video player where initialized on the same page, they both had the same value for some options passed only to the second player. The code is legacy, the videoplayer is implemented as a big fat object.
It turns out that the player store options for a particular feature in a nested object, so even if i clone the player itself with Object.assign(), the inner object is the same reference for both of them 😅 ...
😀 Interesting scenario!
I encountered this problem when I was passing down some data to child components but somehow it was changing data in parent component too.
Thanks for reading!
Great article with great solution.
Thanks for reading!