Lodash Get and Set

Share:
Source Code

This will be a quick tutorial about Get and Set functions from my favorite javascript utility library Lodash.

Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc.Lodash’s modular methods are great for:

  • Iterating arrays, objects, & strings
  • Manipulating & testing values
  • Creating composite functions

Lodash is also available in module format, this means you can NPM install only the functions you need instead of installing the whole library and only use 2% of them.

Installation

You can install Lodash either by stand alone script include or NPM packages, we’ll be focusing on the NPM version because it allows us to take advantage of its modular packaging.

Run the following command to install Lodash’s Get and Set helper functions:

npm i --save lodash.get
npm i --save lodash.set

ok now we have the libraries installed, let’s talk about how and why we might want to use them.

Lodash.set Use Case

Here’s a scenario that came up countless times throughout my career: you get an (sometimes complicated) object back from an api end point, the object has at least three levels of nesting, and depends on what parameter you send to the API, some fields from that object may be empty or have values of unknown data:

const user = {
 name: 'pentacode',
 location: 'house',
 occupation: {
   title: 'developer',
   experience: 'senior',
   skillsets: ['javascript', 'python', 'java']
 }
}

Let’s say we want to access the third skillset of this user, how would you access it? You might write it like this:

const userSkill = user.occupation.skillsets[2];

do you see the problem here? Remember, this data came from an api, and depends on which user you request for, they may or may not have this value available, for example:

const user = {
 name: 'bobby',
 location: 'USA',
 occupation: {
   title: 'developer',
   experience: 'beginner',
   skillsets: ['html']
 }
}

in this case, if you try to perform actions with skillsets[2], this would fail and throw error.  So what we might do is to write defensive code to catch the error:

let userSkill = '';
if (user.occupation && user.occupation.skillsets && user.occupation.skillsets[2]) {
  userSkill = user.occupation.skillsets[2];
}

This fixes the issue, but imo it’s very ugly code and this error checking gets out of hand when you have a really deeply nested object.

Let’s see how we might be able to write this with Lodash.get:

const get = require('lodash.get');
const userSkill = get(user, 'occupation.skillsets[2]', '');

Look at that! Isn’t that clean? the get() function takes three parameters, the first parameter users is the base object you want to access, the second parameter 'occupation.skillsets[2]' is a string of how you would access this particular property of a nested object, and the third is the default fallback for when this value is not available.

If you have a single page application, or a server side application, an uncaught error might crash the whole app!  Lodash.get will safely access the value you specified without crashing your javascript,  This is one of the main reasons I tend to use lodash.get whenever I have to access an object with 3 or more levels of nesting.

Lodash.set Use Case

Now let’s talk about Lodash.set, lodash.set is a very simple function to help you fill in nested object’s property values without the need for you to do any error checking. Let’s say you have an object that looks like this:

user: {
 name: 'pentacode',
 location: 'house',
 occupation: {
   title: 'developer',
   experience: 'senior',
   skillsets: ['javascript', 'python', 'java']
 } 
}

We can use lodash.set to replace a value from any level of this object:

const set = require('lodash.set');
set(user, 'occupation.skillsets[2]', 'ruby');

This will replace the third value of skillsets array with the value ruby .  You can also use it to set new properties:

set(user, ['occupation', 'responsibilities'], ['documentation, tests']);

will modify that user object to be

user: {
 name: 'pentacode',
 location: 'house',
 occupation: {
   title: 'developer',
   experience: 'senior',
   responsibilities: ["documentation, tests"],
   skillsets: ['javascript', 'python', 'java']
 } 
}

Nifty!  I hope you start to see the power of two of my favorite utility functions, this doesn’t even scratch the surface of what Lodash has to offer, so I suggest you check out their EXCELLENT documentation page link below, chances are the utility function you’re about to write already existed in Lodash.

References

Lodash: https://lodash.com/docs/4.17.11

Lodash.set: https://lodash.com/docs/4.17.11#set

Lodash.get: https://lodash.com/docs/4.17.11#get

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode