0

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; 
4
  • You can't use service alone on the right side and do what you're asking. You could do const [ problem, solution ] = service.details.overview; Commented Jan 13, 2021 at 13:37
  • AFAIK you can't rename on destructuring, and again, AFAIK, you can't destructure an object into an array or viceversa. Commented Jan 13, 2021 at 13:38
  • 3
    const { details: { overview: [problem, solution] } } = service; @EmilioGrisolía you can rename using destructuring const { id: ident } = { id: 1 }; declares and assigns obj.id to ident Commented Jan 13, 2021 at 13:39
  • @pilchard Oh that's great! Commented Jan 13, 2021 at 13:41

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.