Nested data can quickly become hard to work with. In most production systems you'll deal with 3-4 levels of object nesting on a regular basis.
When using the normal . operator, if the object on the left side of the . is null or undefined, you'll get a TypeError at runtime! Thankfully, JavaScript has recently added a new operator to make dealing with this headache easier, the optional chaining operator: ?.
const tournament = {
prize: {
units: "dollars",
value: 100,
},
};
const h = tournament.referee.height;
// TypeError: Cannot read properties of undefined (reading 'height')
So, if you're not sure whether the referee property exists (maybe it was sent to us over the network) we can use the optional chaining operator to avoid the error:
const tournament = {
prize: {
units: "dollars",
value: 100,
},
};
const h = tournament.referee?.height;
// h is simply undefined, no error is thrown
Our Textio database is pretty smart - it will only save a value if the value is "truthy" in JavaScript. If it's "falsy", it will just ignore it without errors.
You should be able to do this in 1 line with the optional chaining operator.