Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify default values for null in Lodash or Underscore?

I know the _.defaults function works to put default values for an object with keys that are undefined. However it doesn't work with keys that are null. Is there way to achieve this?

like image 994
JohnnyQ Avatar asked Apr 01 '17 13:04

JohnnyQ


1 Answers

Thanks to @Jacque for the explanation about null values. However due to unfortunate inherited code, the object I'm working on returns null values even though it's intended for undefined. Here's my approach in achieving this in a more declarative way by omitting the null properties which will result into undefined, as a result will create defaults for its values.

const alphabet = {
  a: 'A is for apple',
  // b: undefined,
  c: 'C is for cake',
  d: null,
}
const nonNulls = _.omitBy(alphabet, _.isNull) // Omitting null values.
const longer = _.defaults(nonNulls, {
  b: 'B is for boy',
})

console.info('Longer Way', longer)

// Or even shorter
const shorter = _.defaults(_.omitBy(alphabet, _.isNull), {
  b: 'B is for boy',
})

console.info('Shorter Way', shorter)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 58
JohnnyQ Avatar answered Oct 31 '22 01:10

JohnnyQ