Created
November 12, 2014 21:13
-
-
Save codyromano/54bd9a8f2516266a0dde to your computer and use it in GitHub Desktop.
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
var vehicles = { | |
car: { | |
brand: 'Ferrari' | |
} | |
}; | |
// This check is obviously OK | |
if (vehicles.car.brand) { | |
} | |
// This throws an error for referencing a property of 'stats' because | |
// 'stats' is undefined | |
if (vehicles.car.stats.milesPerGallon) { | |
} | |
// This helper function lets you check if an object has a certain | |
// set of keys in dot notation without throwing an error | |
if (objHasProps(vehicles, 'car.stats.milesPerGallon')) { | |
} | |
function objHasProps (obj, propsList) { | |
var pointer = obj, | |
props = propsList.split('.'), | |
totalProps = props.length, | |
currentKey, | |
i; | |
for (i = 0; i < totalProps; i++) { | |
currentKey = props[i]; | |
if (typeof pointer !== 'object' || !currentKey in pointer) { | |
return false; | |
} | |
pointer = pointer[currentKey]; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment