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.
How to use 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.
Example usage:
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/[email protected](lodash.min.js+lodash.fp.min.js)"></script>
How it works:
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/[email protected]/lodash.min.js"></script>
CLICK HERE to find out more related problems solutions.