Destructuring deep properties

There is a way to handle nested objects and arrays using this syntax. Given the problem described above, a solution would be the following:

let cagingIt = {
      foo: {
        bar: 'Nick Cage'
      }
    };
let { foo: {bar: name} } = cagingIt;

console.log(name); // "Nick Cage"

In this example, foo is referring to the property name “foo”. Following the colon, we then use bar which refers to the property “bar”. Finally, name acts as the variable storing the value.

As for array destructuring, you would handle it like so:

let cagingIt = {
      foo: {
        bar: 'Nick Cage',
        counts: [1, 2, 3]
      }
    };

let { foo: {counts: [ ct1, ct2, ct3 ]} } = cagingIt;
console.log(ct2); // prints 2

It follows the same concept as the object, just you are able to use array destructuring and store those values as well.

Hope this helps!

Leave a Comment