【发布时间】: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