Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Safely Work With Nested Objects in JavaScript

Rahul Banerjee
Better Programming
Published in
3 min readJul 22, 2021

Winding road
Photo by Filip Mroz on Unsplash.

If you have worked with APIs before, you have most likely worked with deeply nested objects. Consider the following object:

Let’s try accessing some values:

console.log(
someObject.data[0].attributes.color
)
// red

This works fine, but what if we try to access the color property of the second element in the data?

console.log(
someObject.data[1].attributes.color
)
// undefined

It prints undefined because the attributes property is empty. Let’s try to access the second element inside the arr property:

In the first case, 2 is printed in the console. However, in the second case, we get an error.

This is because someObject.data[1].attributes is empty and attributes.arr is therefore undefined. When we try to access arr[1], we are actually trying to index undefined, which causes an error.

We could put the code inside a try..catch block to handle the error gracefully, but if you have quite a few cases where you need to access deeply nested values, your code will look verbose.

Let’s look at another scenario. This time, we want to update the value of the element at index 0 in arr:

We get a similar TypeError again.

Safely Accessing Deeply Nested Values

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Rahul Banerjee
Rahul Banerjee

Written by Rahul Banerjee

Software Developer | Views are my own

No responses yet

Write a response