Let’s start with some object I’m going to use for the rest of this example:
Boom. You want to be able to grab data from an object. Rather than:
You can destructure the variable by doing the following:
Pretty neat, considering you don’t have to type eyes twice when you want the variable name to be the same. SWEET!!
Renaming a constant variable while destructuring
Let’s suppose you want to rename a value without changing the results from an API. Note that this API uses snake case rather than camel case. You would have to do the following:
heightInInches will be the name of variable.
Extracting nested data within an object
What if you need to extract multiple variables from nested data? for example, you might want the human’s head, as well as the eyes and ears from within the head. Naively, you might try a two step approach, first getting the head from the human, and then the data within it:
But wait! You can do that all in one shot! Here’s how: