Last active
August 29, 2015 14:14
-
-
Save joshkh/987dc19059971130f44a to your computer and use it in GitHub Desktop.
Find a nested value of an object.
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
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