Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptLodash or Underscore – pick, pickBy, omit, omitBy

Lodash or Underscore – pick, pickBy, omit, omitBy

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 neveropen = {
   "name" : "neveropen",
   "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(neveropen, 
   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 neveropenInfoExceptAmenities = _.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 neveropenInfoExceptInsideArrays = _.omitBy(validGFG, _.isArray);



To get some specific key-value pairs,

// this object contains name & location only.
let neveropenNameAndLocation = _.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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments