Skip to content

Instantly share code, notes, and snippets.

@samermurad
Created November 16, 2020 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samermurad/05f1d143cb347f2a62e66f9bbffc72d6 to your computer and use it in GitHub Desktop.
Save samermurad/05f1d143cb347f2a62e66f9bbffc72d6 to your computer and use it in GitHub Desktop.
lodash getNonNull
const _ = require('lodash');
/**
* File adds a "getNonNull" function to the set of the lodash functions
* function works exactly like `_.get` with one simple exception
* the _.getNonNull returns the default value for null values as well
* just make sure to require this file on your main js/ts file
*
* Example:
* var foo = { bar: undefined: bar1: null }
* with _.get:
* _.get(foo, 'bar', 'default') // "default"
* _.get(foo, 'bar1', 'default') // null
* with _.getNonNull:
* _.getNonNull(foo, 'bar', 'default') // "default"
* _.getNonNull(foo, 'bar1', 'default') // "default"
*/
// eslint-disable-next-line no-prototype-builtins
if (!_.hasOwnProperty('getNonNull')) {
_.getNonNull = function getNonNull(object, path, defaultValue): any {
// eslint-disable-next-line no-useless-call
return _.get.apply(_, [object, path, defaultValue]) || defaultValue;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment