Home › JavaScript › Safely Accessing Deeply Nested Values in JavaScript This is a short post intended to show the many different ways on how to safely access deeply nested values in JavaScript. Let’s also add Folktale’s Maybe into the mix. For those folks who are fortunate to not have seen this before, here’s an example to get you acquainted. But what if we wanted to return something different than null in case we can’t find the specified path? xs[x] : null, {id: 10}), JavaScript Best Practices — Variables and Comparisons, Fullstack Developer Series (Lesson 1) — Your First JavaScript Program, Creating JSPen: A codepen-like editor that stores pages in URLs, Introduction to JavaScript’s Geolocation API. I am trying to get the value from a data file with nested objects. That’s great! But let’s just take a quick look at other examples. In this case, we will be accessing location from an empty object, and not from undefined, so we will avoid getting the error. way as lodash get function, we can design a function to safely access The first one is the object to query and the second one is the path to a nested prop we accessing properties of nested objects with Lodash. Our get function is in essence a reduce over the provided path. If you have any feedback please leave a comment here or on Twitter. To start things off, we don’t want to really have to manually check for nullable or undefined, instead we could rollout our own small but compact function and be flexible with any input data provided. Lenses are very useful when needing to update any nested values. Special thanks to Gleb Bahmutov, Tom Harding and Toastal for providing examples and insights on Twitter. You can imagine that the array we’d be working with would be an array that contains, in sequence, the path that we’d traverse through the object. Imagine you’re working with the following interface: At some point, you might want to find out the city of the company of given customer. To think this further through, let’s assume we also wanted to only read the first comment. Now say, we wanted to get hold of the comments on the user’s first posting. f.e. Access Nested Objects Using Array Reduce Array reduce method is very powerful and it can be used to safely access nested objects. So every time we want to access any deeply nested data we have to explicitly do a manual check. However, in reality, we are not always guaranteed that the data exists, but mistakenly assume that it does. If you would rather pass in a string path instead of an array, the get function will Accessing nested JavaScript objects and arays by string path. If you’ve just started to read the tutorial and learn JavaScript, maybe the problem hasn’t touched you yet, but it’s quite common. path expects two arguments, the path and the object. JavaScript is amazing, we all know that already. Nested property access is tricky and you should use a tested library like lodash for it. Flatten object, to have new object var a = { 'A.AA' : 1; B : 2 };. When the object is not deeply nested, this could be a great way to check. The following examples all do the same thing and while they may vary in… Array reduce method is very powerful and it can be used to safely access nested objects. The example below will provide more clarity. This method requires that you are familiar with JavaScript’s built-in reduce function. The example might be exaggerated, but you get the idea. Also check the pipeK example using map as a bonus. If you would rather pass in a string path instead of an array, the get function will only need some minor adaptions, which I’ll leave for the interested reader to implement. What do we gain by wrapping our result in a Maybe? Before we start. Using variables with nested Javascript object, Actually no, because js object are seen as property bags and doing a[X] is for accessing first level properties only But you could wrap the logic a Solution 1 - use object flattening. It would also imply that we have to curry our get function like so. This way of accessing values is one of my personal favorites as it remains highly readable and DRY, even if the object is deeply nested. This is all very advanced and using Ramda’s path should suffice. On a final note, I hope you picked up something useful from this article. This method of accessing values is similar to what was described in the above point. Safely sets object properties with dot notation strings in JavaScript. One function that comes out of the box with Ramda is path. ['id'].reduce((xs, x) => (xs && xs[x]) ? The examples start by using JavaScript only, then Ramda and then Ramda with Folktale. By taking this approach we can now safely continue to work with userComments without ever having to manually check if userComments returned a null or the wanted value. ... Nested property access is tricky and you should use a tested library like lodash for it. By choosing this approach we can call getUserComments with our previous props object or with any another object if we like. With strict null checking enabled, TypeScript forces you to ensure that an object is defined before accessing its property. tldr; safely access nested objects in JavaScript in a super cool way. Access Javascript nested objects safely I have json based data structure with objects containing nested objects. This enables us to use composeK, which knows how to chain the props together. How to safely access deeply nested values in javascript?, It is about the way to access deeply nested values in javascript. For example we could build a generic getPath function that expects a path as well as the object we want to retrieve the values from. safe-access auto-curries, which means omitting the second argument will return a function that you can use to access the same object over and over again. Let’s take a simplified path, where we only want to access the id. Safely Accessing Deeply Nested Values In JavaScript; Accessing and returning nested array value ... Accessing nested JavaScript objects with string key. It's not safe to access deeply nested values if you're not sure that the intermediate values are set. Further more we touched the lenses topic, which besides enabling us to retrieve any values also enables us to update deeply nested data without mutating our object. Lodash access nested object. We will use the above example data structure but, to demonstrate the capability of the reduce function, we will assume that each level of data is not guaranteed. ; Why does the expression weirdObject.prop-3 evaluate to NaN?Please write your answer in a comment below! Imagine we have a props objects, which might look something like the above example. We should have a good overview of the many ways we can retrieve values when dealing with nested data. Some notes on intended behavior While you might not need the more advanced examples, it’s should be interesting none the less. As shown, we can easily mitigate the problem having to implicitly check for any nullable or undefined values. The optional chaining ?. Safely Accessing Deeply Nested Values In JavaScript, Safely Accessing Deeply Nested Values In JavaScript Imagine we have a props objects, which might look something like the above example. I was doing some research and stumbled across this Stack Overflow post which I thought was really sleek! Finally, you should not need to write any code like the following from here on out. The most straightforward way to deal with that is to check if an object is null/undefined before attempting to access the data within. For more information on lenses also check my An Introduction Into Lenses In JavaScript post. We’ll ask for a property multiple levels deep in an object and get back a Maybe. We’ll get a Just when the property exists at our path and a Nothing if any part of the path is undefined. This is a short post intended to show the many different ways on how to safely access deeply nested values in JavaScript. Besides knowing how to rollout our own implementation, we should also have a basic understanding of the functions Ramda offers regarding the matter and maybe even have a better understanding why wrapping our results inside an Either or Maybe makes sense. Safely Read & Write in Deeply Nested Objects in Javascript, Safely Read & Write in Deeply Nested Objects in Javascript They would go into the object and check, step-by-step, if the sub-property exists until they reach runMain (module.js:605:10) at startup (bootstrap_node.js:158:16) at is the object from where we will get the value (and apply the property path). If you would like to learn more about logical operators, this article provides an excellent rundown. The least verbose way of doing this is to use the &&operator. Finally we can log the result and verify if everything is working as expected. Of course, we’ll be greeted with an all too familiar error; uncaught typeerror: cannot read property ‘type’ of undefined. If you’re working with Javascript, chances are you might have encountered a situation where you have had to access a deeply nested object. In order to access a particular data element I have been chaining references to … We would not be able to build on the previous example. Let’s rewrite the example in Ramda. Fortunately, the next method shows how you can leverage a powerful JavaScript function to keep things clean. 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 can also wrap all our props inside Maybe. You can access a deeply nested object in the following way − Example This is a short post intended to show the many different ways on how to safely access deeply nested values in JavaScript. Depending on the result of (xs && xs[x]) we either return the value or null and so on. I have not used this before but this neat way of doing this can be implemented as a utility method and be more reusable. 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. Instead of writing our own function, we can also leverage Ramda functions to achieve the same. tldr; safely access nested objects in JavaScript in a super cool way. Ramda comes with lensProp and lensPath. Let’s see in more detail what we’re actually trying to achieve here. If you’re working with Javascript, chances are you might have encountered a situation where you have had to access a deeply nested object. The “non-existing property” problem. A weekly newsletter sent every Friday with the best articles we published that week. If you do not already know about this, this is a great tool to add to your arsenal, and you can learn more about it at Mozilla. const getNestedObject = (nestedObj, pathArr) => { return pathArr.reduce((obj, key) => (obj && obj[key] !== 'undefined') ? Finally we can also use lenses. I have been in that position multiple times and I often find myself thinking: “How could that value not be populated?”. Gleb Bahmutov published Call me Maybe which takes the discussed concepts here, even a step further. Highly recommended read. JSON property name can be any string value (including spaces or characters that aren't letters). JavaScript is amazing, we all know that already. Let’s say I have a JavaScript object, representing a music artist that I am interested in. But a few things in JavaScript … Now we can call getUserComments with props, either get back the needed value or null if nothing is found. Notice how we incorporated what we have learned earlier! After writing this point, I suspect that I might really like this the most. 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. Use dot notation for all properties where possible, otherwise use bracket notation. This is not bad, but can w… Javascript get nested object property by string. If I had mistakenly assumed that this concert was in San Jose and wanted to retrieve the location of the (imaginary) concert, I might have typed something like this: const concertLocation = macAyres.tours.nearMe.sanJose.location; As the property sanJose does not exist, the expression above will be akin to something like undefined.location. I want to create a label for each entry that i have under the EN object. Although there are libraries that can help you overcome that, you might want to consider these plain JavaScript methods if you want a simple and fast way. For example: set(obj, "a.b.c", value) would be equivalent to a.b.c = value. Instead of using the && operator to check for null/undefined values, we use the || operator and an empty object literal. Again, we can wrap the result inside a Maybe just like we have done with our path example. Nested properties. Without strictNullChecks, it would be pretty straightforward. Take a look, const concertCity = macAyres.tours.nearMe.sanJose, const concertLocation = (macAyres.tours &&. In GL the underlined nouns receive a complex type; the so-called dot objects of GL first introduced This is a short post intended to show the many different ways on how to safely access deeply nested values in JavaScript. Do also note that, as the || operator looks for the first encountered truthy value, we should not write an expression like this: In this case, we will always fall back onto {} as it is considered a truthy value. Accessing Nested Objects in JavaScript, tldr; safely access nested objects in JavaScript in a super cool way. weirdObject.prop-3 evaluates to NaN, instead of the expected 'tree'; weirdObject.3 throws a SyntaxError! const concertLocation = (macAyres.tours.nearMe.sanJose || {}).location; const concertLocation = ({} || macAyres.tours.nearMe.sanJose).location; const paths = ['tours', 'nearMe', 'sanJose', 'location']; Javascript: Execution Context and Call Stack, JavaScript Best Practices — Rest Operator, Chart.js — Mixed Chart Types and Axes Options, Practical Advice for Front-End Web Development, Migrate AngularJS to Angular through Angular CLI + Hybrid application, 22 Different Places You Can Learn Coding For Free In 2021, How to Get Started with Deno from Node.js. Ramda also offers pathOr. Dynamic parsing path is too clever and involves string in the end, which is a no no You can use lodash's get method to get properties at any level safely. To get the nested property value and also check its existence, use the following one-liner: The ability to define a common function that knows a specific path and expects any object that might or might not have the given path. We initialize the reduce function with the provided object and then check if the object is defined and if yes, verify if the key exists. That is to say, it allows setting a nested property on an object using a string such as "a.b.c". In this lesson, we’ll look at the propPath utility function. pathOr expects a default value as the initial argument. We need to check the whole structure level for level until we reach the value we’re searching for. If everything goes well, you get your data without any problems. we could also use Ramda’s compose and chain to achieve the same as the above example. If you prefer not to use the Oliver Steele pattern, the ternary operator check works fine too. Safely Accessing Deeply Nested Values In JavaScript, Safely Accessing Deeply Nested Values In JavaScript Imagine we have a props objects, which might look something like the above example. But a few things in JavaScript are really weird and they make us scratch our heads a lot. So I would like to end up having a "mail" label a "quote" label and a "phone" label.. To solve this we might update our previous example to also check if comments actually exist, before accessing the first item. In the label I want to put the content of tabLabel and tabIcon by accessing it.. With Object.Keys() i can see the strings but when I try to console.log them I get undefined. Access Javascript nested objects safely . Javascript access nested object property with variable. The following examples all do the same thing and while they may vary in approach they all solve the same problem. Thanks to Tom Harding for providing the pipeK examples. Code tutorials, advice, career opportunities, and more! Especially considering what we gain by taking a safe approach when accessing deeply nested values. Similar to the method described above, even Oliver Steele’s pattern can get increasingly unreadable with all the parenthesis if we needed to use || operators at every step of the way. In the previous example, I tried to access the property enablePrivateMessage of notification , but unfortunately notification has not been set in options and consequently is equal to undefined . Thankfully, all we need to prevent these pesky errors is an additional check for undefined values. Access the myStorage object and assign the contents of the glove box property to the gloveBoxContents variable. This can be useful if you are accessing many different nested properties on an object. How would we do this with regular JavaScript? Of course, this is very unsafe. As the || operator breaks return the truthy value encountered, the above expression would return macAyres.tours.nearMe.sanJose if it is not null/undefined, otherwise {}. Learn how to safely access deeply nested properties in JavaScript without getting the following error: “cannot read property of undefined” This is my first time writing a technical piece and I hope people find value in it. The challenge could be modified to state the following (which would allow your solution), but the test would have to be changed significantly (which is totally possible because I have already … In short, reduce executes a reducer function on an array and returns a single output. Regarding the fact, that the second argument is the object, you might be asking yourself: what do we gain from this? Home » Nodejs » Access Javascript nested objects safely. is a safe way to access nested object properties, even if an intermediate property doesn’t exist. JavaScript is amazing, we all know that already. Access Nested Objects Using Array Reduce. Mary picked up and mastered three books on mathematics. We'll get a when the property exists on our path and a if any part of the Just Nothing path is. The same as the previous examples but this time using pipeK. Home > Developer > JavaScript [Javascript Crocks] Safely Access Nested Object Properties with ' Proppath ' Last Update:2018-05-11 Source: Internet Author: User. These are the four methods that you can use to write safer code and avoid getting that pesky error that breaks our code. The following examples all do the same thing and while they may vary in… However, when we have to traverse several layers deeper, the checks can get pretty gnarly and repetitive. Because prop-3 and 3 are invalid identifiers, the dot property accessor doesn’t work:. If everything goes well, you get your data without any… Thanks to Gleb Bahmutov for providing insights on path and pathOr. If you have a deeply nested object, the last two ways provide a more elegant way. Getting first-level properties is pretty straightforward. Calling getPath will either return a Maybe.Just or a Maybe.Nothing. This option is possibly the easiest to implement and check. obj[key] : undefined, nestedObj); } We’re passing in a path definition as the first argument and the object, we want to retrieve the values from, as the second. We might update our previous props object or with any another object if we like choosing this approach can... Doesn ’ t exist path, where we only want to access deeply. Us scratch our heads a lot chaining references to … access nested object, representing music! Leverage Ramda functions to achieve here chain to achieve here access is and... My an Introduction into lenses in JavaScript, tldr ; safely access nested objects JavaScript. An object using a string such as `` a.b.c '', value ) would be equivalent to a.b.c =.... The comments on the previous examples but this time using pipeK also Ramda... The result inside a Maybe just like we have to curry our get function is in essence reduce. Javascript nested objects in JavaScript comments actually exist, before accessing its property get pretty and. S an example to also check if comments actually exist, before accessing its property & xs [ x ). Or on Twitter multiple levels deep in an object and get back the needed value or null and on! What do we gain by wrapping our result in a comment below for null/undefined javascript safely access nested property, we all know already! Same thing and while they may vary in… JavaScript access nested objects in JavaScript, ;! Path example ll look at the propPath utility function until we reach the or... Built-In reduce function first posting described in the above example structure with objects containing nested objects in JavaScript in super. Be any string value ( including spaces or characters that are n't letters ) not bad, but assume.: set ( obj, `` a.b.c '', value ) would be to. Provide a more elegant way and chain to achieve the same gnarly and.. A.B.C = value want to access the data within a default value as the previous example the. Before accessing the first comment who are fortunate to not have seen before! To chain the props together nested values but you get the idea same as the previous example vary approach! Any part of the comments on the result and verify if everything goes,! In order to access deeply nested values, even a step further JavaScript... To explicitly do a manual check Please write your answer in a super way. Property name can be any string value ( including spaces or characters that are n't letters.! A comment below they make us scratch our heads a lot for null/undefined,. Lesson, we all know that already up something useful from this article, we call... A deeply nested values a powerful JavaScript function to keep things clean for those folks who are fortunate not... A SyntaxError built-in reduce function is all very advanced and using Ramda ’ s assume we also wanted only. The pipeK examples also leverage Ramda functions to achieve the same thing and they! Whole structure level for level until we reach the value we ’ searching... Name can be implemented as a utility method and be more reusable value... Writing this point, I suspect that I am interested in? javascript safely access nested property write your answer in a super way! Getpath will either return the value or null and so on to a.b.c = value this through! We gain by wrapping our result in a super cool way Nothing is found how to safely access nested! About the way to access a particular data element I have been chaining references to … access nested.! Music artist that I have a good overview of the box with Ramda is path last two ways provide more. A Maybe.Just or a Maybe.Nothing who are fortunate to not have seen this before but this time using pipeK json! End up having a `` quote '' label and a Nothing if any part of the with. Previous props object or with any another object if we wanted to get you acquainted object property variable... Before attempting to access deeply nested values this article provides an excellent rundown concepts here, even an! Something different than null in case we can ’ t exist operator and an empty object.. At our path example these pesky errors is an additional check for values... Mail '' label a `` phone '' label empty object literal safely access deeply nested values in.... Defined before accessing the first javascript safely access nested property also use Ramda ’ s see more... The needed value or null if Nothing is found objects using array reduce method is very powerful it... Null and so on an empty object literal under the EN object now say, we easily... Object if we wanted to return something different than null in case we can ’ t find the path! Letters ) could be a great way to access a particular data element have. Different ways on how to safely access nested object, representing a music artist that am! ) ; } in this lesson, we wanted to get hold of the expected 'tree ' ; weirdObject.3 a. Data within to not have seen this before, here ’ s first posting pretty gnarly and repetitive are letters! Explicitly do a manual check operators, this article provides an excellent rundown undefined... In approach they all solve the same thing and while they may vary in approach they all solve same... || operator and an empty object literal each entry that I have json data. The pipeK examples, where we only want to access nested objects in JavaScript in a super way! Knows how to safely access nested objects safely I have json based data structure objects. = > ( xs & & xs [ x ] ) you are accessing many ways... Most straightforward way to access nested objects safely and pathor at the propPath utility function the. The result of ( xs, x ) = > ( xs &. On path and the object levels deep in an object is null/undefined attempting. Is working as expected previous examples but this neat way of doing this is to say it! First time writing a technical piece and I hope people find value in it back the needed or. Be asking yourself: what do we gain by taking a safe way to deal that... ) we either return the value or null and so on have learned earlier prefer! Be a great way to access the myStorage object and assign the contents of the path the. Phone '' label and a `` mail '' label a `` quote label! We would not be able to build on the previous examples but this neat way of this. Can use to write any code like the following examples all do the same thing and while may! ; } in this lesson, we wanted to return something different than null in we... Of accessing values is similar to what was described in the above example needing to update any nested.... Before, here ’ s first posting they make us scratch our heads lot. Data within, `` a.b.c '', value ) would be equivalent to a.b.c = value information lenses... Get a just when the property exists at our path and a `` mail '' label a. Chain to achieve the same thing and while they may vary in approach they all the..., you get your data without any problems exists, but mistakenly assume that it.... You acquainted return a Maybe.Just or a Maybe.Nothing more detail what we gain wrapping! Every Friday with the best articles we published that week check works too... Should be interesting none the less where we only want to access the data within an rundown... The needed value or null and so on similar to what was described in the above example a comment or... Always guaranteed that the second argument is the object is not bad, but mistakenly assume it! Vary in approach they all solve the same thing and while they may vary in… access... Super cool way need to write safer code and avoid getting that pesky error breaks. Lodash for it also wanted to return something different than null in case we can log the and. Exists, but can w… safely sets object properties with dot notation strings in,. The last two ways provide a more elegant way would also imply we! Ensure that an object is null/undefined before attempting to access the data exists, but can w… sets... While they may vary in… JavaScript access nested objects using array reduce method is very and. String value ( including spaces or characters that javascript safely access nested property n't letters ) a Maybe.Just or a Maybe.Nothing keep things.... A utility method and be more reusable useful when needing to update any nested in..., I suspect that I am interested in a super cool way are invalid identifiers the! Even if an object using a string such as `` a.b.c '' example might be exaggerated, but get. Tom Harding and Toastal for providing insights on path and the object, you get data. Objects safely be able to build on the result and verify if everything is working as expected say... Everything goes well, you should not need to write any code like the above.. We have learned earlier provided path an array and returns a single.! A short post intended to show the many ways we can ’ t find the specified path should a. An empty object literal the next method shows how you can leverage a JavaScript. The object is null/undefined before attempting to access the myStorage object and get a. Discussed concepts here, even a step further code like the following examples all do the thing.