Blackbird Blackbird - 1 year ago 58
Javascript Question

How to detect that a multi-level object has an undefined or null property?

In many places in my code, I have checks similar to the one below. It's very verbose, and ugly. Is there is better way? FYI, I'm using Lodash in all my projects, so I have access to that powerful library.

if (myAssessments[orderId].report &&
myAssessments[orderId].report[categoryProductCode] &&
myAssessments[orderId].report[categoryProductCode].categories &&
myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]) {

// Do something related to
// myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]

Answer Source

Since you use lodash, you might use the has method:

_.has(obj,[orderId, 'report', categoryProductCode, 'categories', comment.categoryId])

Or the get method to get the value of the object path:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download