Skip to content

Instantly share code, notes, and snippets.

@defvol
Created January 27, 2017 18:07
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 defvol/3a708d18957827949689d4cc58cc10f5 to your computer and use it in GitHub Desktop.
Save defvol/3a708d18957827949689d4cc58cc10f5 to your computer and use it in GitHub Desktop.
Wrapper to handle accessing undefined properties on a nested object (catches TypeErrors)
/**
* Add a standard error handling routing when accessing nested keys
* On TypeError (accessing undefined property) it will return empty array
* Will also take care of wrapping single elements in an array
* usage: safeparse(() => parsedXml.status.events.event)
* @param {Function} accessor just returns a nested key
* @returns {Array}
*/
function safeparse (accessor) {
try {
return [].concat(accessor())
} catch (e) {
return []
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment