1. use try / catch
In your statement, you:
- 26 potential sources for reference errors (16 missing objects, 10 arrays beyond the borders).
What handles try / catch best. Work with the same type of errors from a block of code and processing in one place. Therefore, if you do not want to deal with each potential error individually, try / catch the simplest and best tool that you have at your disposal. It works and you can identify the problem:
var w = {} try {wxyz} catch(e) {e}
TypeError: Cannot read property 'y' from undefined (...)
Alternatively, if you need more control, you can
2. check all links up
If necessary, even if some properties do not work, you can check each link. eg:.
var sdValid = data && data.actions && data.actions.length>1 && data.actions[0].causes && data.actions[0].causes.length && data.actions[1].causes[0].shortDescription; var owner = sdValid ? data.actions[1].causes[0].shortDescription : 'default value'; this.response = { owner : owner,
You can easily make it more readable if you
3. expand your own control link
this.response = { owner : nestget(data, 'nobody') .prop('actions', 1) .prop('causes', 0) .prop('shortDescription') .value(), // return shortDescription if you got this far or 'nobody' build_version : nestget(data, '0.0.0') .prop('actions', 0) .prop('parameters', 0) .prop('value') .value(), // return value if you got this far or '0.0.0' // ... etc }; // Custom - easy to use reference checker function nestget (obj, default) { var valid = false; this.default = default; this.obj = obj; var that = this; return { prop : propChecker, value : getValue } function propChecker (prop, i) { // implementation omitted for brevity } function getValue () { return value; } }
4. use the library
Last but not least, you can always use the library. Personally, I like the way XPath looks for XML trees, so I would suggest using something like JSONPath to find nested objects in a data structure. eg.
this.response = { owner : jsonpath(data, '$..shortDescription[0]'), build_version jsonpath(data, '$.actions[0].parameters[0].value'), // no error // ... etc }
However, there are many options (e.g. lodash / underscore, as indicated in the comment).