Blackbird Blackbird - 14 days ago 5
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

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

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

https://lodash.com/docs/4.16.6#has

Or the get method to get the value of the object path: https://lodash.com/docs/4.16.6#get

Comments