Destructure Nested Objects in JavaScript

J.C. Hiatt
InstructorJ.C. Hiatt
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 5 years ago

It’s commonly known that you can destructure objects in ES6, but did you know you can also destructure values from deeply nested objects?

In this lesson, we will cover destructuring deeply nestled objects and also providing default values in case the value you destructure isn’t present in the object.

Instructor: [00:00] Say we wanted to destructure only the secondary value out of this nested bench press object. We can destructure nested objects in JavaScript by saying const muscles, because that's the first object we're destructuring. Then secondary, because that's the value we wanted to get, and then finally, equals bench press.

[00:23] If we console.log this secondary value out, we get triceps. We can destructure as many levels deep as we need to. If we only wanted this primary value, we could come down here, and we could say, const variations, and we could destructure the standard.

[00:43] Then we could destructure muscles and finally grab the primary value out of there. Don't forget to set it equal to the top level object, which is bench press. Then we will console.log primary, and we have chest, which is what we were expecting.

[01:04] Now, there are a couple of caveats here. First off, we can get a hard to read if you destructure too many levels deep. Keep that in mind when using this feature. Secondly, the values you are trying to destructure may not always exist.

[01:18] Maybe you're trying to get some data from an API. For some reason, it doesn't come back the way you were expecting. In this case, we may want to set a default value for primary just in case it doesn't exist.

[01:29] We could say primary equals unknown. That way, if we come up here and all of a sudden this primary value does not exist, we still get a value of unknown rather than throwing an error.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today