selectn

Resolves deeply-nested object properties via dot or bracket-notation for Node.js and the browser.

selectn

Select n-levels deep into an object by providing a dot/bracket-notation query string.

  • selectn is simple, tiny and exposes a fluent API
  • ES5 and non-ES5 compatible

component

$ component install wilmoore/selectn

bower

$ bower install selectn

npm

$ npm install selectn

Given the following object:

var talk = {
  info: { name: 'Go Ahead, Make a Mess' }
};

the generated function can be immediately invoked for error-free and immediate access to deeply nested properties.

selectn('info.name')(talk);
// => 'Go Ahead, Make a Mess' 

Given the following list:

var talks  = [
  { info: { name: 'Go Ahead, Make a Mess' }},
  { info: { name: 'Silex Anatomy' }},
  { info: { name: 'Unit Testing in Python' }},
  { info: { name: 'Setting the Stage' }}
];

the generated function can be used as a predicate for a functor:

var query = selectn('info.name');
talks.map(query);
// => [ 'Go Ahead, Make a Mess', 'Silex Anatomy', 'Unit Testing in Python', 'Setting the Stage' ] 

In larger, data-driven applications, there tends to be a need to do a lot of deep object access which can quickly lead to code like this:

var name;
if (contact && contact.info && contact.info.name) {
  name = contact.info.name.full || 'unknown';
}

The following is much more concise:

var name = selectn('info.name.full')(contact) || 'unknown';

Alternatively, you can use typeof; however, it's limited in it's fluency and tends to make otherwise easy to read code look more obtuse than it really is. There are also solutions involving eval and/or Function (eval in indisguise). Thanks, but no thanks.

MIT