Search code examples
javascriptreactjstypescriptecmascript-6destructuring

How to destructure an array within an object and rename the variables created from it?


I want to destructure the following object (simplified here):

export class Service = {
  ...
  details: {
    overview: [
      {
        title: {
          de: 'Mock Example',
          en: 'Mock Example',
        },
        description: {
          de: 'Lorem ipsum...',
          en: 'Lorem ipsum...',
        },
      },
      {
        title: {
          de: 'Mock Example 2',
          en: 'Mock Example 2',
        },
        description: {
          de: 'Lorem ipsum...',
          en: 'Lorem ipsum...',
        },
      },
    ],
    ...

I only want to have "service" on the right side and name the index 0 of the overview array "problem" and the index 1 of the overview array "solution" like this:

const { problem, solution } = service;

I've tried the following approach, but it doesn't work that way. And I don't quite understand how I can rename the variables to "problem" and "solution"?

  const { 
    details: { 
      overview[0]: { 
        ...
      }, 
    }, 
    details: {
      overview[1]: {
        ...
      }
    }
  } = service; 

Solution

  • I guess, that's what you're after:

    const service = {
        details: {
            overview: [{
                    title: {
                        de: 'Mock Example',
                        en: 'Mock Example',
                    },
                    description: {
                        de: 'Lorem ipsum...',
                        en: 'Lorem ipsum...',
                    },
                },
                {
                    title: {
                        de: 'Mock Example 2',
                        en: 'Mock Example 2',
                    },
                    description: {
                        de: 'Lorem ipsum...',
                        en: 'Lorem ipsum...',
                    },
                },
            ]
        }
    }
     
    const {details: {overview: [problem, solution]}} = service
          
    console.log(problem, solution)