Skip to content

Instantly share code, notes, and snippets.

@boutell
Created September 16, 2013 19:30
Show Gist options
  • Save boutell/6585360 to your computer and use it in GitHub Desktop.
Save boutell/6585360 to your computer and use it in GitHub Desktop.
Dot notation is a cool feature of mongodb that lets you set nested properties of an object. It's not hard to support this in your own JavaScript code. Here's the _get method I use in the joinr npm module to allow access to sub-properties of 'o' via syntax like 'name.last'. Also works for arrays. And if you pass a function, that function is calle…
// This supports: foo, foo.bar, foo.bar.baz (dot notation,
// like mongodb) and also passing in a custom accessor function
_get: function(o, accessor) {
var fn = accessor;
if (typeof(accessor) === 'string') {
fn = function(o) {
var keys = accessor.split(/\./);
_.each(keys, function(key) {
o = o[key];
});
return o;
};
}
return fn(o);
}
Copy link

ghost commented Sep 16, 2013

This is quite useful for a problem I'm working on. Now I wonder how hard mimicking the positional $ would be...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment