#2

Avoiding Undefined in Deeply Nested Objects

2019-08-12

TAGS: javascript

The Problem

When checking for a property on a heavily nested object, you can sometimes run into undefined errors.

It's not so bad with something like user.name. You can use the && operator like this:

user && user.name

This only tries to access name on user if user exists.

With this object: user.company.documents.handbook there are multiple points where it could all fall apart. The solution using && starts to get really messy.

Destructuring Solution

We can use destructuring assignment to pull the values out.

const { user: { company: { documents: { handbook:  = 'default' } = {} } = {} } = {} } } = this

This gives us fallbacks with each = {} and also makes the variables more managable to work with.

Learned this one from Brady Sutton.

Lodash Solution

Lodash gives us the get method where you pass it an object, then the path you want, then the default value you'd like returned if anything comes back undefined.

_.get(this, 'user.company.documents.handbook', 'default')

Learned this one from Brady Sutton.

Optional Chaining Solution

We have a great solution coming to JavaScript soon called Optional Chaining. This will open up this syntax:

user.address?.zipcode