5 Must Know Lodash Methods

camskithedev

Cameron Lucas

Posted on July 28, 2021

5 Must Know Lodash Methods

Lodash is a Javascript utility library, that helps you work with arrays, objects, strings, and just write fewer functions in general. Let's talk Lodash and some of its most useful methods!

1.) _.get()

The _.get() method can help us find an element in an object. If an element is not found at the specified path we can specify a default value for the _.get() method to return.

const foodObj = {
  favFoods: [
    "Pizza",
    "Chicken Nuggets",
    "Lasagna",
    { favCandy: "Sour Boys Candy" },
  ],
};

// We will use the _.get() method to find my favorite candy.

const myFavCandy = _.get(foodObj, 'favFoods[3].favCandy', 'Chocolate')

// mymyFavCandy => "Sour Boys Candy"
console.log(myFavCandy)
Enter fullscreen mode Exit fullscreen mode

A few things to notice here are

  • The _.get() method can receive three arguments, the first being the object we want to get an element from. The second is the path. The third is the default we want to return if an element was not found.

  • The path to the element is a string.

  • The default retuned value can be any data type (object, string, number, null, etc). By default, the _.get() method will return undefined if an element was unable to be found.

2.) _.find()

You might think that the _find() method is similar to the _.get() method, and yes, they will both return a value we are looking for but, there is a few key differences that are important to understand. Let's first take a look at the _.find() method.

const adoptableDogs = [
  { name: "Rex", age: 7, breed: "German Sheperd" },
  { name: "Sundance", age: 4, breed: "Timber wolf - Mutt" },
  { name: "Milo", age: 0.8, breed: "Husky" },
  { name: "Snowflake", age: 3, breed: "White Lab" },
  { name: "Chip", age: 3, breed: "Pug" },
  { name: "Bolt", age: 5, breed: "White Lab" },
];

// The _.find method will iterates over an object or an array and retun the first element that returns true.
const myNewBestFirend = _.find(
  adoptableDogs,
  // This function will be called on every iteration.
  (obj) => obj.breed === "White Lab" && obj.age > 2,
  2
);

// myNewBestFirend => { name: 'Snowflake', age: 3, breed: 'White Lab' }
console.log(myNewBestFirend);
Enter fullscreen mode Exit fullscreen mode

Kinda cool right? We should talk about those differences though.

  • The _.find() method also takes three arguments, but unlike the _.get() method, the first argument can be an array or an object.

  • The second argument is the function that will fire on every iteration. I used a function in the example above to help solidify this concept. This is important to understand and hopefully helps demonstrate the possibilities.

  • The third argument is the starting index of the collection. Since the _.find() method iterates over every element in a collection. Performance is something to think about with large data sets/collections. You can specify a starting index for the _.find() method to start its search at.

3.) _.map()

The _.map method will iterate over a collection(array, object), and return a new array based on the return value of the function called on each iteration. Let's take a peek.

const adoptableDogs = [
  { name: "Rex", age: 7, breed: "German Sheperd" },
  { name: "Sundance", age: 4, breed: "Timber wolf - Mutt" },
  { name: "Milo", age: 0.8, breed: "Husky" },
  { name: "Snowflake", age: 3, breed: "White Lab" },
  { name: "Chip", age: 3, breed: "Pug" },
  { name: "Bolt", age: 5, breed: "White Lab" },
];

// The _.map method will iterate over the adoptableDogs array and return a new array with all of the dogs' names.
const adoptableDogsNames = _.map(adoptableDogs, (dog) => dog.name);

// adoptableDogsNames => [ 'Rex', 'Sundance', 'Milo', 'Snowflake', 'Chip', 'Bolt' ]
console.log(adoptableDogsNames);
Enter fullscreen mode Exit fullscreen mode

As you can see the _.map() method returns a new array with just the dogs' names as the elements in the array.

4 _.set()

The _.set() method is the opposite of the _.get() method. It will set the value of an element at a specified path. The first argument is the object or array, the second is the path, and the third is the value you desire to set.

const adoptableDogs = [
  { name: "Rex", age: 7, breed: "German Sheperd" },
  { name: "Sundance", age: 4, breed: "Timber wolf - Mutt" },
  { name: "Milo", age: 0.8, breed: "Husky" },
  { name: "Snowflake", age: 3, breed: "White Lab" },
  { name: "Chip", age: 3, breed: "Pug" },
  { name: "Bolt", age: 5, breed: "White Lab" },
];

// Sets the age of the dog at the second index of the adoptableDogs array to 1.
_.set(adoptableDogs, "[2].age", 1);

// adoptableDogs[2] => { name: 'Milo', age: 1, breed: 'Husky' }
console.dir(adoptableDogs[2]);
Enter fullscreen mode Exit fullscreen mode

5.) _.debounce()

This is one of the most powerful lodash methods in my opinion. It can also be very hard to understand what it does and when you might want to use it. The _.debounce() method will return a function. The function returned by the _.debounce() method will delay its invocation until a specified number of milliseconds has elapsed since the last time the function was invoked.

Let's say you were listening to a DOM event (scroll, resize, etc) or API/Webhook route, the event or API may be called multiple times a day or even second. Now let's say you only want to run the function once every 24 hours even if the event or API is called multiple times a second, this is where a debounced function would help. Let's take a peek at the code!

const updateData = _.debounce(
  () => {
    // Code here! We might update some kind of data that might need to be updated once a day.
    console.log("Went and grabbed some new data");
  },
  1000 * 60 * 60 * 24, // 1 Day Timeout
  {
    // defines if the invocation of the function is on the trailing or leading edge of the timeout.
    leading: true,
    trailing: false,
  }
);

// We can call the function returned by the _.debounce method.
updateData();
Enter fullscreen mode Exit fullscreen mode

Conclusion

Lodash is a very helpful utility library, and it has a bunch of helpful methods! We have just barely scraped the surface of lodash in this post. If you would like to know more about the _.debounce method and take a deeper dive into it, check out this blog post by David Corbacho - Debouncing and Throttling Explained Through Examples

You can also follow me on GitHub, Youtube, and Twitter.

💖 💪 🙅 🚩
camskithedev
Cameron Lucas

Posted on July 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related