When doing deep and nested destructuring, you can destructure array items by index
function nestedArrayAndObject() {
const info = {
title: 'Once Upon a Time',
protagonist: {
name: 'Emma Swan',
enemies: [
{name: 'Regina Mills', title: 'Evil Queen'},
{name: 'Cora Mills', title: 'Queen of Hearts'},
{name: 'Peter Pan', title: `The boy who wouldn't grow up`},
{name: 'Zelena', title: 'The Wicked Witch'},
],
},
}
// const title = info.title
// const protagonistName = info.protagonist.name
// const enemy = info.protagonist.enemies[3] <----
// const enemyTitle = enemy.title
// const enemyName = enemy.name
const {
title,
protagonist: {
name: protagonistName,
enemies: {
3: { // destructure nested array by index
title: enemyTitle,
name: enemyName,
},
},
},
} = info;
return `${enemyName} (${enemyTitle}) is an enemy to ${protagonistName} in "${title}"`
}
console.log(nestedArrayAndObject());
// Zelena (The Wicked Witch) is an enemy to Emma Swan in "Once Upon a Time"
Thanks to @KentDodds for the example on his ES6 and Beyond YouTube series.