Selectn

selectn

Resolve deeply-nested object properties via dot/bracket-notation string or array path while mitigating TypeErrors.

refactor this:
person && person.info && person.info.name && person.info.name.full
into:
selectn('info.name.full', person)
or this:
contacts.map(function (contact) {
  return contact && contact.addresses && contact.addresses[0]
})
into:
contacts.map(selectn('addresses[0]')))

Installation

> npm install selectn --save

Features

  • Mitigates boilerplate guards like if (obj && obj.a && obj.a.b && obj.a.b.c) { return obj.a.b.c; }.
  • Mitigates TypeError Cannot read property '...' of undefined.
  • Supports multiple levels of array nesting (i.e. group[0].section.a.seat[3]).
  • Supports dashed key access (i.e. stats.temperature-today).
  • If value at path is a function, the value returned is the return value of invoking the function.
  • Partial application is automatic when you omit the second argument (i.e. selectn is curried).
  • Property accessor generated by selectn can be passed to higher-order functions like map or filter.
  • Compatible with modern and legacy browsers, Node/CommonJS, and AMD.
  • Haskell style parameter order allows for pointfree style programming.

Non-Features

  • No eval or Function (see: eval in disguise).
  • No typeof since, typeof is not a real solution to this problem but can appear to be due to the way the global scope is implied.

GIF FTW!

selectn Checkout the project's readme.md for more examples.

Suggest a module

Comments