What is object destructuring?
Object destructuring, or the destructuring assignment syntax, is a way to pull elements out of an object with less typing in the long run. It becomes particularly helpful in React after typing the word “props” so many times that you can’t see straight, or when you have nested objects.
So, let’s say we’ve got a basic object representing a trip to Italy (#2020…one can dream, right?):
So, we’ve got an object that is nested with various objects and arrays. But what if we want to grab the hotel we’re staying at in Naples? Is there an easier way than italianVacation.stops[“Naples”].hotel? This is where object destructuring comes in. Step one would be destructuring out the key-value pairs in the largest object.
Now, if we console.log startDate, we would get “06–01–2022”, and so on and so forth. The trick is to wrap these new variables you are defining inside the curly braces, and the name of the larger object you are trying to destructure on the right side of the equal sign. And from there, we can go even further inside of the nesting:
First, I broke down the stops by naming them by city, then grabbed Naples and broke down its key-value pairs of sight and hotel. Now, both hotel and italianVacation.stops.Naples.hotel will return “Romeo Hotel”.
Starting to see how this comes in handy, huh? Honestly, this is so simple that I’m a little ashamed that I waited so long to play around with it.
There aren’t many rules with this one…you don’t even need to name the variables the same thing as the key name (but I tend to for practical purposes).
This is just the basics of destructuring…you can also use this for arrays (with square brackets instead of curly braces) and there are a lot more advanced ways to use this to your advantage as well. For more information, I’d highly recommend checking out the documentation on MDN.