Ramda: Suggestion: Null-safe `get`

Created on 8 Apr 2016  路  4Comments  路  Source: ramda/ramda

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);
});

Most helpful comment

See path, pathOr and propOr.

All 4 comments

See path, pathOr and propOr.

I think path already does what you want. Ramda also already has propOr, and pathOr for default values. You might also look at lensPath which creates a lens for a particular path with which you can then view, set, or adjust the value with over.

... although the real killer feature of lenses is that they compose

Cool, thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alexcarruthers picture alexcarruthers  路  3Comments

FranzSkuffka picture FranzSkuffka  路  3Comments

woss picture woss  路  3Comments

ashaffer picture ashaffer  路  4Comments

davidchambers picture davidchambers  路  4Comments