Skip to content

Instantly share code, notes, and snippets.

@codyromano
Created November 12, 2014 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyromano/54bd9a8f2516266a0dde to your computer and use it in GitHub Desktop.
Save codyromano/54bd9a8f2516266a0dde to your computer and use it in GitHub Desktop.
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