Skip to content

Instantly share code, notes, and snippets.

@joshkh
Last active August 29, 2015 14:14
Show Gist options
  • Save joshkh/987dc19059971130f44a to your computer and use it in GitHub Desktop.
Save joshkh/987dc19059971130f44a to your computer and use it in GitHub Desktop.
Find a nested value of an object.
Object::hasprop = (propstring) ->
split = propstring.split '.'
obj = @
i = 0
while i < split.length
if !obj or !obj.hasOwnProperty split[i] then return false
obj = obj[split[i]]
i++
obj
# Usage:
testobj = color: green: shade: 'palm'
if value = testobj.hasprop 'color.green.shade'
console.log 'Value found:', value
# Return a friendly 'fase'
if !value = testobj.hasprop 'color.blue.shade.light'
console.log 'Thanks for bailing gracefully!', value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment