import { getOr } from 'lodash/fp';
I would like to know how getOr works, because I was unable to find specific documentation to explain it.
import { getOr } from 'lodash/fp';
I would like to know how getOr works, because I was unable to find specific documentation to explain it.
The getOr()
method behaves in a very similar way to the regular get() method in the non-functional lodash library:
_.get(object, path, [defaultValue])
The above is the usage for get
in regular lodash. To use it, you need to provide the object
you want to grab the value from, the path
to the value, and an optional defaultValue
if the path doesn't exist within the object.
getOr()
:The following is the usage for _.getOr()
:
_.getOr(defaultValue)(path)(object)
Much like _.get()
from regular lodash, the above returns the value located at path
in object
, or the defaultValue
if the path does not exist within the object.
You may have noticed that you must provide a defaultValue
above in order to pass the object and the path arguments. If you're certain your path will always lead to a value (and don't need a default value) then that's what the _.get(path)(object)
method is for.
const {getOr} = _;
const object = {'a': [{ 'b': { 'c': 3 } }]};
console.log(getOr("default")("a[0].b.c")(object)); // 3
console.log(getOr("default")(['a', '0', 'b', 'c'])(object)); // 3
console.log(getOr("default")("a.b.c")(object)); // "default"
<script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)"></script>
The definition for _.getOr()
wraps the regular lodash _.get()
definition, except that it is curried, the arguments are flipped, and the default value has to be supplied (as you wouldn't be able to supply the other curried arguments if you didn't provide the default value). Using lodash, you could implement _.getOr
yourself like so:
const {get, rearg, ary, curry} = _; // normal get method
const getOr = curry(rearg(ary(get), [2, 1, 0]));
const object = {'a': [{ 'b': { 'c': 3 } }]};
console.log(getOr("default")("a[0].b.c")(object)); // 3
console.log(getOr("default")(['a', '0', 'b', 'c'])(object)); // 3
console.log(getOr("default")("a.b.c")(object)); // "default"
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>