Created
September 16, 2013 19:30
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is quite useful for a problem I'm working on. Now I wonder how hard mimicking the positional $ would be...