Lodash's `get` function
Edit:
Now we have optional Chaining
available (TypeScript 3.7 & ES2020) which elegantly solves this issue without relying on an external library. I'll write another blog post about this.
The Problem:
Often we can't be sure if the data we are working with in web apps is already available or that it has certain properties (in Objects). So often we need to first check if the nested property is accessible.
In a typical React
component this would look something like this:
let streetName =
(this.props.user &&
this.props.user.address &&
this.props.user.address.streetName) ||
null
resulting in null
if any of the properties in the props
Object don't exist.
It looks ugly and doesn't tend to be very readable.
The Solution:
Lodash
's get
function gives us an elegant way to shorten the code and make it more readable:
_.get(object, path, [defaultValue])
Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
let streetName = _.get(this.props, 'user.address.streetName', null)
It's cleaner, easier to read and makes more sense than a line of &&
followed by ||
....
Also, lodash is very modular, so you can just import the parts you actually need and your bundle won't get bloated just because you need a single function from lodash.
import get from 'lodash/get'