An obvious limitation of assoc
functions is that they cannot update multiple properties at a time. We need to write multiple assoc
statements. This is where merge
functions come into the picture. They can update multiple properties in a single statement.
As its name indicates merge
functions accept two objects as arguments and merge all their properties into a single new object. If the same key exists in both the input objects, one of them will be given priority over the other based on which merge function we are using.
There are mergeLeft
and mergeRight
functions. mergeLeft
will give higher priority to keys of the first argument object (left side argument) over the second argument object (right side argument). In case of conflict, the right side object's keys will be overwritten with the left side object's and vice versa in mergeRight
.
mergeLeft
Let's see what mergeLeft
does.
As you can see in the above example, the properties of the order
object were overwritten by the left value, that is { name: "ORD2" }
.
To understand what happens when we say overwrites, see the updatedCustomerOrder
object. the value of the customer
attribute was completely overwritten instead of firstName
and lastName
being appended to the existing attributes. So, essentially the following happened under the hood:
mergeRight
Let's see how mergeRight
is different from mergeLeft
.
As you can see in the above example, order
's properties were overwritten by the right value, i.e tmpOrder
's properties. The name
and customer
properties also got overwritten.
In this case, the following happened: