Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Created July 5, 2012 13:04
Show Gist options
  • Select an option

  • Save hughfdjackson/3053556 to your computer and use it in GitHub Desktop.

Select an option

Save hughfdjackson/3053556 to your computer and use it in GitHub Desktop.
navigating by a string w/ dot syntax
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