【问题标题】:Destructuring objects with hyphenated keys使用连字符键解构对象
【发布时间】:2018-01-05 01:57:46
【问题描述】:

在我的应用程序中,我正在从响应标头向我的商店添加一些分页元数据。其中一个键的名称是Per Page,在对象字面量中转换为per-page

是否有可能解构连字符键?我已经尝试将它变成一个计算属性,将它的驼峰式封装,并将它变成一个纯字符串,但无济于事。有什么建议吗?

const { page, [per-page], total } = response.headers;

const { page, perPage, total } = response.headers;

const { page, "per-page", total } = response.headers;

【问题讨论】:

  • 你不能。解构后的键成为范围内的变量名,因此必须是有效的 JavaScript 标识符。您只需要在单独的行上执行此操作:const {page, total} = reponse; const perPage = response['per-page'];

标签: javascript ecmascript-6 destructuring


【解决方案1】:
const { page, "per-page": perPage, total } = response.headers;

这会将带有“每页”键的值写入perPage 常量。

【讨论】:

  • 谢谢。 MDN 上或文档中是否有解释此解决方法的地方?
  • @CarlEdwards 我不认为有什么地方有这样的例子,但例子 "Assigning to New Variable Names" 涵盖了一般行为。
  • 太棒了。再次感谢。
猜你喜欢
  • 2017-02-11
  • 1970-01-01
  • 2019-05-28
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
  • 2020-09-11
相关资源
最近更新 更多