documentcloud/underscore — pull request #1106 by neocotic (2013-05-08 20:00:37+00:00)
Title: _.resolve: Simple dot & bracket notation parser

Recently I've been finding needs for simple evaluation of dot and bracket notation and I've been unable to find a good solution. At one point I considered using `_.template` for this but this seemed like overkill, and the performance and security overhead of using the underlying `Function` constructor (much like evil `eval`) make it very off-putting, at least for this behaviour.

With `_.resolve` you can easily do the following:

``` javascript
var data = { foo: 'bar', fu: [{ baz: 'bingo' }] };

_.resolve(data, 'foo');
// "bar"

_.resolve(data, 'fu[0].baz');
// "bingo"

_.resolve(data, 'fu[1].baz');
// undefined

_.resolve(data, 'foo["length"]');
// 3

_.resolve(data, 'fizz');
// undefined
```

One thing I'd like to note is that, due to the lightweight nature of the code, the following patterns are valid in `_.resolve` but not in JavaScript:

``` javascript
// Only numbers in dot notation would throw "Unexpected number" in JavaScript
_.resolve(data, 'fu.0.baz');
// "bingo"

// Optional quotation marks (single or double) in bracket notation for cleaner/simpler paths
_.resolve(data, '[foo][0]["baz"]');
// "bingo"
```

Before I start copying this code to all my projects I thought it would be best to see if this feature would be welcomed in Underscore. Possible uses:

``` html

Underscore.js

```

The idea of parsing either user-defined, untrusted, dynamic, or hard coded (e.g. property paths taken from element attributes or a JSON response value) is obviously the main benefit here as raw JavaScript will clearly out-perform standard usage (i.e. `var value = foo.bar.fu.baz` will be more efficient than `var value = _.resolve(foo, 'bar.fu.baz')`).

Finally, I can see this being a great asset when couple with something like `_.memoize`.