Safely Accessing Deeply Nested Values In JavaScript

Many Ways To Safely Access Nested Data.

Intro

This is a short post intended to show the many different ways on how to safely access deeply nested values in JavaScript. The following examples all do the same thing and while they may vary in approach they all solve the same problem.

Before we start. Let’s see in more detail what we’re actually trying to achieve here.

const props = {

user: {

posts: [

{ title: 'Foo', comments: [ 'Good one!', 'Interesting...' ] },

{ title: 'Bar', comments: [ 'Ok' ] },

{ title: 'Baz', comments: [] },

]

}

}

Imagine we have a props objects, which might look something like the above example. Now say, we wanted to get hold of the comments on the user’s first posting. How would we do this with regular JavaScript?

// access deeply nested values...

props.user &&

props.user.posts &&

props.user.posts[0] &&

props.user.posts[0].comments

This might look like something we might come across and it’s sensible to the point, that we want to make sure a key or index exists before we try to access it. To think this further through, let’s assume we also wanted to only read the first comment. To solve this we might update our previous example to also check if comments actually exist, before accessing the first item.

// updating the previous example...

props.user &&

props.user.posts &&

props.user.posts[0] &&

props.user.posts[0].comments &&

props.user.posts[0].comments[0]

So every time we want to access any deeply nested data we have to explicitly do a manual check. To clarify why this is troublesome, just imagine we didn’t want to check the users posts, but instead wanted to know the blog title of the user’s last comment. We would not be able to build on the previous example.

// accessing user's comments

props.user &&

props.user.comments &&

props.user.comments[0] &&

props.user.comments[0].blog.title

The example might be exaggerated, but you get the idea. We need to check the whole structure level for level until we reach the value we’re searching for.

Ok, so now that we have a better understanding of what problem we’re actually trying to solve, let’s take a look at the different ways we can approach this. The examples start by using JavaScript only, then Ramda and then Ramda with Folktale. While you might not need the more advanced examples, it’s should be interesting none the less. Especially considering what we gain by taking a safe approach when accessing deeply nested values.