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 for object 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.
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 have stopped using lodash. I will use the recursive function
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 like the recursive function.
Great! make your own common function to handle all cases.
Enjoy!