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!


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'
]);