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.

UPDATE: If you’d like to learn more about lodash, check out my free e-book about Functional Programming in JavaScript.

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:

var a = {
  name: "John",
  age: 23
var b = {
  job: "Analyst"

…instead of copying properties manually:

const c = {
  age: a.age,
  job: b.job

…one could write:

const c = _.assign(a, b);

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:

const c = _.assign({}, a, b);<br>

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.