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!!!
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.
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.
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.
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.
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'))
You can rely on the fact that null
, undefined
, etc. are falsy, and use the ||
operator.
_.get(room, 'nickname') || _.get(room, 'name')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With