【问题标题】:How to destructure an array within an object and rename the variables created from it?如何解构对象中的数组并重命名从中创建的变量?
【发布时间】:2021-04-18 12:41:58
【问题描述】:

我想解构以下对象(此处简化):

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...',
        },
      },
    ],
    ...

我只想在右侧有“服务”,并将概览数组的索引 0 命名为“问题”,将概览数组的索引 1 命名为“解决方案”,如下所示:

const { problem, solution } = service;

我尝试了以下方法,但它不起作用。而且我不太明白如何将变量重命名为“问题”和“解决方案”?

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

【问题讨论】:

  • 您不能在右侧单独使用service 并按照您的要求进行操作。你可以做const [ problem, solution ] = service.details.overview;
  • AFAIK 你不能在解构时重命名,同样,AFAIK,你不能将对象解构为数组,反之亦然。
  • const { details: { overview: [problem, solution] } } = service; @EmilioGrisolía 您可以使用解构重命名 const { id: ident } = { id: 1 }; 声明并将 obj.id 分配给 ident
  • @pilchard 哦,太好了!

标签: javascript reactjs typescript ecmascript-6 destructuring


【解决方案1】:

我猜,这就是你所追求的:

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)

【讨论】:

    猜你喜欢
    • 2022-12-12
    • 2018-07-24
    • 2022-10-16
    • 2022-01-20
    • 2019-12-21
    • 2020-11-26
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多