Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null values with lodash

This is simple json

  {
    home: 68
    id: 1
    name: "RL Conference Room"
    nickname: null
    setpoint: 32.34
    sleep: 58
  }

When I get empty key this lodash function works

_.get(room, 'keyName', 'whenKeyNotFound')

But as you can see above i am getting null value in nickname So I want to replace it with name but this doesn't work.

_.get(room, 'nickname', 'name')

Is there any function in lodash which does the trick?

Thank you!!!

like image 826
Dark Knight Avatar asked Oct 17 '18 13:10

Dark Knight


People also ask

How to check null value using lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNull() method is used to find whether the value of the object is null. If the value is null then returns true otherwise it returns false.

How do you remove undefined and null values from an object using Lodash?

To remove a null from an object with lodash, you can use the omitBy() function. If you want to remove both null and undefined , you can use . isNull or non-strict equality.

Is null or undefined Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.

How do you check undefined in Lodash?

isUndefined() method is used to find whether the given value is undefined or not. It returns True if the given value is undefined. Otherwise, it returns false.


3 Answers

In one level scenario and since (in your case) null is also an undesired result it seems you are better of without lodash and simply do this:

room.nickname || room.name 

It would actually be shorter and achieve the same result in your case.

You could also do:

let name = _.defaultTo(room.nickname, room.name)

_.defaultTo to protects you from null, NaN and undefined

So in the case above you would get the obj.name but if you have nickname set you would get that.

In scenarios where you have a long path you can utilize _.isEmpty in a custom function like this:

const getOr = (obj, path, def) => {
    var val = _.get(obj, path)
    return _.isEmpty(val) ? def : val
}

This will handle your null as well as other scenarios as per _.isEmpty docs.

You can simply then use as:

getOr(room, 'nickname', room.name)

And you can nest it:

getOr(room, 'nickname', getOr(room, 'name', 'N/A'))
like image 68
Akrion Avatar answered Sep 28 '22 10:09

Akrion


You can rely on the fact that null, undefined, etc. are falsy, and use the || operator.

_.get(room, 'nickname') || _.get(room, 'name')
like image 28
AKX Avatar answered Sep 28 '22 10:09

AKX


Since null is falsy, you can do

_.get(room, 'nickname') || 'name'

.get only returns the third argument if the result is undefined

see: https://lodash.com/docs/4.17.10#get

like image 45
Owen Avatar answered Sep 28 '22 11:09

Owen