Adam Lambert
Adam Lambert

Reputation: 1421

Dealing with javascript undefined objects/arrays within an if statement

I am catching errors from an Ajax response. The kind of error that comes back depends on where it was thrown and I need to look out for certain ones.

I know the error variable always exists but past this I have to check the existence for each level, otherwise risk getting a TypeError: Cannot read property '0' of undefined error.

I am currently doing:

if (error.response && error.response.data && error.response.data.errors 
&& error.response.data.errors[0].title === 'no_space') {
   //do something
}

But there must be a better way?

Upvotes: 0

Views: 48

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could reduce the keys and take the final value for a check.

var keys = ['response', 'data', 'errors', 0, 'title'];
if (keys.reduce((o, k) => (o || {})[k], error) === 'no_space') {
    // ...
}

Upvotes: 1

Related Questions