Skip to content
Related Articles
Open in App
Not now

Related Articles

Lodash or Underscore – pick, pickBy, omit, omitBy

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 30 Jun, 2020
Improve Article
Save Article
Like Article

Javascript is Everywhere. The Javascript is used widely and it’s not limited to just only in your web browser but also widely used in the server-side as well. JavaScript is used by 95% of all the websites.

Lodash or Underscore makes coding in Javascript much easier & also makes our code minimal, it works with arrays, numbers, objects, strings, etc.

We can use Lodash basically with any JS based library or framework, for instance w/ Angular, React, VueJs, Node.Js, Vanilla JS, etc.

Lodash’s modular methods are great for:

  1. Iterating arrays, objects, & strings
  2. Manipulating & testing values
  3. Creating composite functions

Let’s go through very basic and most used Lodash methods which makes our day to day life easier & increase readability of our code.

1. pickBy

2. pick

3. omitBy

4. omit and so on..

Pick and Omit are contrary of each other, as the name describes omit is used to omit/exclude parameters from the object as per our needs on the other hand pick is used to pick/include elements defined.

Examples:

let geeksforgeeks = {
   "name" : "geeksforgeeks",
   "location" : "NCR",
   "vacancies" : null,
   "amenities" : ['free_breakfast','health_insurance'],
   "interview_process" : ["DSA","Technical","HR"]
};



Now, to get only valid values from your object i.e., except null & undefined

/* now validGFG object contains only 
valid (!null & !undefined) key-value pairs. */
let validGFG = _.pickBy(geeksforgeeks, 
   v => !_.isUndefined(v) && !_.isNull(v));



To get all key value pairs from our validGFG object except some, we can simply do this :

// this object contains all key-value pairs except amenities.
let geeksInfoExceptAmenities = _.omit(validGFG, ['amenities']);



We can do one step further to eliminate all the arrays/string(s)/number/etc. from our object,

/* this object will contain only name & location just
because we omitted all the array type from our object. */
let geeksInfoExceptInsideArrays = _.omitBy(validGFG, _.isArray);



To get some specific key-value pairs,

// this object contains name & location only.
let geeksNameAndLocation = _.pick(validGFG, ['name','location']);



We can use many combinations of above stated functions & handle our arrays, objects and much more quite easily.

For much more, you can go through docs of Lodash.

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!