Created
July 5, 2012 13:04
-
-
Save hughfdjackson/3053556 to your computer and use it in GitHub Desktop.
navigating by a string w/ dot syntax
This file contains hidden or 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
| var dotGet = function(o, propStr){ | |
| var getProp = function(o, name){ | |
| return ( typeof o == 'object' && o != null && name in o ) ? o[name]: undefined | |
| } | |
| return propStr.split('.').reduce(getProp, o) | |
| } | |
| // tests | |
| var o = { x: { y: { z: 'test', bar: null } } } | |
| console.log(dotGet(o, 'x.y.z')) // 'test' | |
| console.log(dotGet(o, 'x.y')) // { z: 'test', bar: null } | |
| console.log(dotGet(o, 'x.x.y')) // undefined | |
| console.log(dotGet(o, 'x.y.z.foo')) // undefined | |
| console.log(dotGet(o, 'x.y.z.bar.quux')) // undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment