Destructuring deep properties

JavascriptEcmascript 6

Javascript Problem Overview


I recently started using ES6's destructuring assignment syntax and started to get familiar with the concept. I was wondering if it's possible to extract a nested property using the same syntax.

For example, let's say I have the following code:

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

I know I am able to access extract foo into a variable by doing:

// where foo = { bar: "Nick Cage" }
let { foo } = cagingIt;

However, is it possible to extract a deeply nested property, like bar. Perhaps something like this:

// where bar = "Nick Cage"
let { foo[bar] } = cagingIt;

I've tried finding documentation on the matter but to no avail. Any help would be greatly appreciated. Thank you!

Javascript Solutions


Solution 1 - Javascript

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!

Solution 2 - Javascript

If you have lodash installed, you can use one of the following:

_.get

var object = { 'a': [{ 'b': { 'c': 3 } }] };
 
_.get(object, 'a[0].b.c');
// => 3

or if you need multiple keys.

_.at

var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
 
_.at(object, ['a[0].b.c', 'a[1]']);
// => [3, 4]

You can also safely pair _.at() up with with Array destructuring. Handy for json responses.

[title, artist, release, artwork] = _.at(object, [
  'items[0].recording.title',
  'items[0].recording.artists[0].name',
  'items[0].recording.releases[0].title',
  'items[0].recording.releases[0].artwork[0].url'
]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDomView Question on Stackoverflow
Solution 1 - JavascriptDomView Answer on Stackoverflow
Solution 2 - JavascriptetoxinView Answer on Stackoverflow