Combining two objects in lodash

I’m a huge fan of the lodash library. It encourages functional programming style in JavaScript and as a result lets you write less error-prone and more readable code.

Some time ago I discovered the assign (extend) function which copies properties from target object(s) and assigns them to the target object. It also returns the target object. This is very handy whenever you want to combine properties from two objects into one object.

For example, given these two objects:

…instead of copying properties manually:

…one could write:

The result in c would be the same. However, with assign, object a will be modified. What I often wanted to do is to “merge” a and b into c but not modify neither a nor b.

Recently I learnt that the way to do this is the following:

With above code we copy properties of a and b into a new empty object and than return this new object. This is exactly what we wanted to achieve.

Check out this post where I write more about lodash. It is a part of a course in Functional Programming in JavaScript.

Leave a Reply