Nested Destructuring

By  on  

Destructuring in JavaScript can initially feel confusing but the truth is that destructuring can make your code a bit more logical and straight forward. Destructuring does look a bit more complex when you're looking for a property several objects deep, so let's have a look at how to do that!

Simple destructuring looks as follows:

const { target } = event;

Here we use {} and = to name a variable the same as the property name (you can also use an alias while destructuring!). Grabbing a nested object value is a bit more complicated, however:

// Object for testing
const x = { y: { z: { a: 1, b: 2} } }

// Get "b"
const { y: { z: { b } } } = x;

console.log(b); // 2
console.log(z); // z is not defined
console.log(y); // y is not defined

Here we an object-like syntax with {} and : to set a var based on the nested obect property. Note that only the last nested property is given as a variable; the parents we reference along the way do not.

To get a reference to both b and y, for example, you can use a comma:

const { y, y: { z: { b } } } = x;

console.log(b); // 2
console.log(y); // {z: {…}}

Destructuring can take a while to get used to but, the more I use it, the more I appreciate how simple my code can be: no "dot" hell and less overall code!

Recent Features

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

  • By
    Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

Incredible Demos

  • By
    MooTools Star Ratings with MooStarRating

    I've said it over and over but I'll say it again:  JavaScript's main role in web applications is to enhance otherwise boring, static functionality provided by the browser.  One perfect example of this is the Javascript/AJAX-powered star rating systems that have become popular over the...

  • By
    Create a Photo Stack Effect with Pure CSS Animations or MooTools

    My favorite technological piece of Google Plus is its image upload and display handling.  You can drag the images from your OS right into a browser's DIV element, the images upload right before your eyes, and the albums page displays a sexy photo deck animation...

Discussion

  1. I find the second solution much more readable and I think it scales better when the destructuring gets even more complex.

  2. Filip Voska

    You say “no “dot” hell and less overall code”. This example is in contradiction to your statement.
    1. It is not less code, it is actually more code
    2. You also mention “dot” hell, but you just replaced each dot character with TWO curly braces characters. So you are in even deeper hell now.

    I honestly don’t think that

    const { y: { z: { b } } } = x;

    is nicer than simply writing

    const b = x.y.z.b

    Don’t get me wrong, (nested) destructuring is cool, but for me personally this is a poor example of good usage of nested destructuring. For me personally this would actually be an example where I would rather use dot notation instead of destructuring.

    • Ben C

      I agree, I would use the second, “traditional” method in this or a similar case. Like many examples, it is contrived, and hence doesn’t look terribly sensible. But the thing about object destructuring is that it is most useful for concisely grabbing multiple properties from an object with minimal repetition.

        const data = {
          category: "motoring",
          articles: [],
          categories: {
            motoring: {},
            fishing: {},
            sports: {}
          },
          user: {
            name: "...",
            bio: "...",
            avatar: {},
          }    
        };
      
        const { 
          articles, 
          categories: { [data.category] } : category, 
          user: { name }    
        } = data;
      

      which is arguably slightly preferable to:

        const articles = data.articles;
        const category = data.categories[data.category];
        const name = data.user.name;
      

      …and could be even better in an even less contrived real world case!

  3. kia

    What do you do if you want y, z, and b to be defined?

    • Simply separate by comma — I added an example to the post. Great question!

  4. Ben C

    Great! I use object and array destructuring extensively but have never actually thought about whether you could get nested properties.

    Might be a good idea to add some array examples too?

  5. The way you have covered this topic is very nice. Thanks.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!