Simplifying your code with Lodash

Reading time ~2 minutes

I have been using the Lodash library a lot lately, then I decided to list here some functions that I consider very useful. You will notice how it can simplify your code, making it more elegant, cleaner, and functional.

Lodash, is a tool kit of JS functions that provides methods for manipulating objects and collections. It’s like a utility belt!

Filtering

In order to filter collections, we can use the filter method. It’s returns only those objects that contain the specified key, and it’s also supports nested objects.

let pets = [
  {name: 'Snoopy',   likes: [{toy: 'ball'}]},
  {name: 'Meow',     likes: [{food: 'milk'}]},
  {name: 'Garfield', likes: [{food: 'milk'}, {food: 'lasagna'}]}
];
_.filter(pets, {likes: [{food: 'milk'}]});
 
//returns [{name: 'Meow', likes: [...]}, {name: 'Garfield', likes: [..., ...]}]

Grouping objects

The groupBy method takes an array of objects and groups them by some field or condition.

let pets = [
  {name: 'Snoopy',   type: 'dog']},
  {name: 'Meow',     type: 'cat'}]},
  {name: 'Garfield', type: 'cat'}]}
];

_.groupBy(pets, 'type');

//returns {dog: [{name: 'Snoopy',...}],
//         cat: [{name: 'Meow', ...}, {name: 'Garfield', ...}]}

Merging Objects

The merge method takes multiple source objects, and merges their properties together into an object.

let obj1 = {id: 1, tag: 'js', values: [1, 2]};
let obj2 = {name: 'John'};
let obj3 = {id: 2, tag: null, values: [3, 4]};

_.merge(obj1, obj2, obj3);

//returns {id: 2, tag: null, values: [3, 4], name: 'John'}

Selecting properties to create a new object

The pick method creates an object composed of the picked object properties.

let pet = {name: 'Meow', type: 'cat', color: 'white'};

_.pick(pet, ['name', 'color'])

//returns {name: 'Meow', color: 'white'}

Chaining

Lodash allows us to chain the collection functions instead of using a bunch of temporary variables, making your code more readable.

Let’s say that we have an array of pets and we need:

  1. get all pets that are dogs
  2. get just the dog name
  3. order by name
  4. join the names with commas
let pets = [
  {name: 'Goofy', type: 'dog'},
  {name: 'Snoopy', type: 'dog'},
  {name: 'Dino', type: 'dog'},
  {name: 'Garfield', type: 'cat'},
];

_.chain(pets)
 .filter({type: 'dog'})
 .map('name')
 .sort()
 .join(',')
 .value();

//returns  Dino,Goofy,Snoopy'

More about Lodash

There are hundreds of useful functions available in the Lodash library. Here I just listed some simple examples, but they’re enough to realize how useful it can be for your Js projects.

If you want to learn more, Lodash website is an excellent resource. Feel free to write your questions in the comment box.

Thanks for reading. Until next time!

Spike and TDD - Exploring the unknown

Spikes and TDD - Exploring the unknown Continue reading

Testing Websockets with Spring

Published on May 23, 2016

Bundling Js modules with WebPack

Published on April 25, 2016