Lodash has get (similar to Clojure's get-in), to grab for nested properties in a null-safe manner:
const obj = {};
get(obj, ['some', 'nested', 'property']) //=> null
As opposed to:
const obj = {};
obj.some.nested.property //=> Boom!
Lodash also supports a default value, which is quite handy. I guess I want a shorthand for this:
defaultTo(42, prop('nested', prop('something', obj)))
I guess it might have to be two functions as variadic functions and auto-currying doesn't mix to well.
const get = curry((path, target) => {
return path.reduce((res, p) => res && res[p], target);
});
const getWithDefault = curry((path, defaultVal, target) => {
return path.reduce((res, p) => {
const val = res && res[p];
return val === null || val === undefined || typeof val === 'number' && isNaN(val) ? defaultVal : val;
}, target);
});
See path, pathOr and propOr.
... although the real killer feature of lenses is that they compose
Cool, thanks!
Most helpful comment
See
path,pathOrandpropOr.