Member-only story
How To Safely Work With Nested Objects in JavaScript
Be careful when working with nested objects
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.