Dark Knight
Dark Knight

Reputation: 1083

How to handle null values with lodash get

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!!!

Upvotes: 10

Views: 16456

Answers (4)

Anjan Talatam
Anjan Talatam

Reputation: 3996

use a custom get function

Create a utility function that works on top of the lodash get function to handle null values.

How customGet() works?

Returns the default value if the value turns out to be null or undefined

Note: null values are defaulted only if the default value is provided.

import lodashGet from "lodash/get";

type TGetParams = Parameters<typeof lodashGet>;

export function customGet(
  object: TGetParams[0],
  path: TGetParams[1],
  defaultValue?: TGetParams[2]
) {
  const value = lodashGet(object, path);

  if (defaultValue !== undefined) {
    return value ?? defaultValue;
  }

  return value;
}

Open in Codesandbox

Upvotes: 0

Akrion
Akrion

Reputation: 18515

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'))

Upvotes: 10

Owen
Owen

Reputation: 81

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

Upvotes: 2

AKX
AKX

Reputation: 168903

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

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

Upvotes: 8

Related Questions