If you know about the situation with copying by value vs copying by reference you can skip over what I am writing here. If not it is important to note that making a copy of an object is not as easy as making a copy of a primitive value such as a String or Number. With primitives you can just do something like this:
Objects on the other hand are a bit more of a pain, because when I attempt to copy them the same way I would a primitive, you do not end up with a copy, you end up with a reference.
Often this is the effect that is desired, when doing something like grabbing a reference to a DOM element, or something to that effect. However if it is a situation in which I want to change values without effecting the object I am referencing, I need to do something to make an actual copy of the object.
There are many ways to do this, but because this is a post on lodash, there is the _.clone method that works well If I just want to make a quick shallow copy of an object.
this works just fine as long as what is often called a ‘shallow clone’ with work okay, when dealing with more complex objects it becomes more important to find ways to go about preforming what is called a ‘deep clone’.
To understand the problem that can happen with shallow cloning take a look at the following.
This happens because although I am making a new object rather than just referencing one that all ready exists, one of the properties is another Object (arrays are objects), and as such that still remains a reference. So I need some kind of way to make not just one new object, but a new object for every object in the object as well. In short I need to deep clone an object.
The _.cloneDeep method in lodash works basically the same way, only it deep clones the object. As such I just have to make one simple change to the above example to get it to be a full copy of everything in the object.
Also when it comes to the new ES2015+ standards there is plenty more to cover with this, but this is just one of my lodash posts, so that is another ball of wax.