Autoplay

    Destructure Nested Objects in JavaScript

    J.C. HiattJ.C. Hiatt

    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.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss