Two cool Lodash methods for objects

Lodash is a great library, which has a number of cool methods that help in dealing with arrays, objects and strings, or creating composite functions. Some methods were quite often available earlier in Lodash than in native JavaScript counterparts and they are also browser safe.

I will show you two methods below that can come handy when one works with large objects.

Installation

Lodash is available both on server side and for browser. To install Lodash, go to the project folder, and type npm i lodash --save, then require it at the top of the working file, where you want to use it:

const _ = require('lodash');

The symbol of Lodash is the underscore (_).

Alternatively, if you want to use it in the browser, place the path to the file inside script tags and place it before your main JavaScript file. Lodash is also available via CDN.

The _.keyBy method

We can often come across an array of objects, where we need to find a specific object. It can be error prone to refer to the index of the object, especially when we have an array length of 453, for example. In this case, it could come handy if the objects had their own specific property, which could be easily referred to. The _.keyBy method just does that.

Let’s assume we have an array of musician objects where each musician has a first name, a last name, a gender and an instrument property:

const musicians = [
  {
    firstName: 'Elton',
    lastName: 'John',
    gender: 'male',
    instrument: 'piano'
  },
  {
    firstName: 'Kate',
    lastName: 'Voegele',
    gender: 'female',
    instrument: 'guitar'
  },
  {
    firstName: 'Jim',
    lastName: 'Pebbles',
    gender: 'male',
    instrument: 'triangle'
  }
];

We can make an object of objects from the array, where the individual objects have a key we want. In this case, we want the values of the instrument property to be that key:

const musiciansByInstrument = _.keyBy(musicians, 'instrument');

The first argument is the collection we want to rearrange, which is the musicians array, and the values of the properties we want for our objects become the second argument (instrument). If we log musiciansByInstrument, we will get the following:

// { piano:
//    { firstName: 'Elton',
//      lastName: 'John',
//      gender: 'male',
//      instrument: 'piano' },
//   guitar:
//    { firstName: 'Kate',
//      lastName: 'Voegele',
//      gender: 'female',
//      instrument: 'guitar' },
//   triangle:
//    { firstName: 'Jim',
//      lastName: 'Pebbles',
//      gender: 'male',
//      instrument: 'triangle' }
// }

First, we got an object of objects from the array of objects. Each object has a key which was originally its instrument value. Now we can easily get the details of the guy who plays the triangle:

const triangleGuy = musiciansByInstrument.triangle;

We will get the whole object for Jim Pebbles. Great!

We have one thing to be careful of when using _.keyBy. What happens, if we also have Eric Clapton, who also plays the guitar, a bit slowly but quite well actually?

{
  firstName: 'Eric',
  lastName: 'Clapton',
  gender: 'male',
  instrument: 'guitar'
}

Let’s have a look again:

const musiciansByInstrument = _.keyBy(musicians, 'instrument');

will return

// { piano:
//    { firstName: 'Elton',
//      lastName: 'John',
//      gender: 'male',
//      instrument: 'piano' },
//   guitar:
//    { firstName: 'Eric',
//      lastName: 'Clapton',
//      gender: 'male',
//      instrument: 'guitar' },
//   triangle:
//    { firstName: 'Jim',
//      lastName: 'Pebbles',
//      gender: 'male',
//      instrument: 'triangle' }
// }

So as we can see, Kate Voegele got overridden by Eric Clapton, because they both play the guitar and only one instance of the same key (in this case, guitar) may occur in an object. We can only use this method safely when we are confident that the values of the properties are all different (like the _id in a MongoDB collection or a bank account number).

The _.groupBy method

Sometimes we have a hard time avoiding double or even triple for loops because we need to deal with multiple arrays at the same time.

Let’s say that we iterate over an array of elements and invoke a function on each element. Then, we would need to call a function on the male musicians for some reason. To reduce the number of elements to loop through, a possible solution is to extract the male musicians in a separate array and do our stuff directly with them.

The _.groupBy method comes in handy in this case:

const musiciansByGender = _.groupBy(musicians, 'gender');

This method returns an object of objects, where the key of each object will become the gender. So we will have two objects (because we have two genders) with keys being female and male, and their values are an array of the original objects:

// { male:
//    [ { firstName: 'Elton',
//        lastName: 'John',
//        gender: 'male',
//        instrument: 'piano' },
//      { firstName: 'Jim',
//        lastName: 'Pebbles',
//        gender: 'male',
//        instrument: 'triangle' } ],
//   female:
//    [ { firstName: 'Kate',
//        lastName: 'Voegele',
//        gender: 'female',
//        instrument: 'guitar' } ]
// }

From here, we can easily get the male musicians and do with them whatever we want (codewise, of course):

const maleMusicians = musiciansByGender.male;

Here we only need to iterate through an array of two objects instead of three. It’s also easy to see that the real benefit of this method becomes obvious when we need to deal with hundreds or thousands of objects. Instead of iterating over all of them, we can greatly reduce the number of elements if we know what we want to do and how we need to handle data.

Conclusion

Lodash library is very useful when we need to deal with large amount of data. Two of their great methods are _.keyBy and _.groupBy, which can be used to improve performance and decrease the amount of data our functions need to work with. It’s worth spending some time reading the documentation of Lodash, and it’s probable that we can find a suitable method for almost every situation we come across in our daily work.

Of course, many Lodash methods (_.map, _.filter etc.) can be replaced with native JavaScript.

So why use Lodash? It’s a personal preference. These methods are often easier to use than their corresponding native methods or have an easier solution to the same problem. If you actively use Lodash in your daily work, you will probably write _.map instead of the native .map anyway in order to have some consistency in your code and the library is also safe to use. It’s worth giving it a try!