javascriptarraysdestructuringobject-destructuring

Destructuring object consist of deep nested object of arrays


I'm trying to destructure setup shown below. I need to get text: Zelena The Wicked Witch is an enemy to Emma Swan in Once Upon a Time.

OK, it's easy to get properties from objects info and protagonist, but I can't get data from an array of objects (enemies) for particular object, for instance for row number 3. I tried many different expressions, with no luck.

Any help would be highly appreciated.

function nestedArrayAndObject() {
  // refactor this to a single line of destructuring...
  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 {
      protagonist: {
          enemies[3]: {name: enemyName}          
      }, 
      protagonist: {
          enemies: {title: enemyTitle}
      },
      protagonist: {name: protagonistName},
      title: title 
 } = info;
 
return `${enemyName} (${enemyTitle}) is an enemy to ${protagonistName} in "${title}"`
}

nestedArrayAndObject();

Solution

  • You can achieve as:

    const {
        title,
        protagonist: {
            name: protagonistName,
            enemies: [, , , { name: enemyName, title: enemyTitle }],
        },
    } = info;
    

    function nestedArrayAndObject() {
        // refactor this to a single line of destructuring...
        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,
            protagonist: {
                name: protagonistName,
                enemies: [, , , { name: enemyName, title: enemyTitle }],
            },
        } = info;
    
        return `${enemyName} (${enemyTitle}) is an enemy to ${protagonistName} in "${title}"`;
    }
    
    nestedArrayAndObject();