Nested object in array - object destructing es6
Nested destructuring can be confusing sometimes. You can always check on the Babel compiler to get the ES5 equivalent and understand how it works
So, this code:
const test = [{ count: 0 }, { whatever: 1 }, { total: 2 }];
const [{ count }, , { total }] = test
console.log(count, total)
Gets trasnpiled to:
var count = test[0].count;
var total = test[2].total;
As you can see, index = 1
item is ignored (MDN) and we are only destructuring the 0
th and 2
nd index properties
Since, we are on the topic of destructuring array objects, this can be used in much more advanced ways. You can destructure an item at any index like this:
const test = [{ count: 0 }, { count: 1 }, { count: 2 }];
const { 2: { count } } = test;
console.log(count)
This gets the count at index 2
. This code is equivalent to:
var count = test[2].count;
Note that, we are using {}
here instead of []
. This instructs the compiler to get the count
at the key: 2
. You can also get the length
of the array using this type of destructuring:
const { length } = test; // same as test.length
You can make it even more dynamic with a computed object property name:
const test = [{ count: 0 }, { count: 1 }, { count: 2 }];
const index = 2;
const { [index]: { count } } = test;
console.log(count)