I have json based data structure with objects containing nested objects. In order to access a particular data element I have been chaining references to object properties together. For example:
var a = b.c.d;
If b or b.c is undefined, this will fail with an error. However, I want to get a value if it exists otherwise just undefined. What is the best way to do this without having to check that every value in the chain exists?
I would like to keep this method as general as possible so I don't have to add huge numbers of helper methods like:
var a = b.getD();
or
var a = helpers.getDFromB(b);
I also want to try to avoid try/catch constructs as this isn't an error so using try/catch seems misplaced. Is that reasonable?
Any ideas?
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
The nested objects are utilized to store the object's properties with another object. The dot and square bracket notations are employed to access the properties of objects in JavaScript. In the first syntax, the dot operator is used, while the second way is to access the property using bracket notation.
The basic definition of an object in JavaScript is a container for named values called properties (keys). Sometimes, we need to create an object inside another object. In this case, it's called a nested object.
ECMAScript2020, and in Node v14, has the optional chaining operator (I've seen it also called safe navigation operator), which would allow your example to be written as:
var a = b?.c?.d;
From the MDN docs:
The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
Standard approach:
var a = b && b.c && b.c.d && b.c.d.e;
is quite fast but not too elegant (especially with longer property names).
Using functions to traverse JavaScipt object properties is neither efficient nor elegant.
Try this instead:
try { var a = b.c.d.e; } catch(e){}
in case you are certain that a
was not previously used or
try { var a = b.c.d.e; } catch(e){ a = undefined; }
in case you may have assigned it before.
This is probably even faster that the first option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With