ES6 — How to destructure from an object with a string key?

ぃ、小莉子 提交于 2019-12-22 03:08:40

问题


I have an object

{
  hello_en: 'hello world',
  'hello_zh-CN': '世界您好',
  something: 'nice day',
  something_else: 'isn\'t it'
}

being passed into a function

function(data) {
  const { hello_en, hello_zh-CN, ...rest } = data
  // do some stuff with hello_en and hello_zh-CN
  // so some other stuff with rest
}

but of course hello_zh-CN is not a valid key name.

I am unable to write

const { hello_en, 'hello_zh-CN', ...rest } = data

as that gives an error.

How can I destructure an object's properties when one of the keys is a string?


回答1:


Destructure it by providing a valid key name like

  const { hello_en, 'hello_zh-CN': hello_zHCN, ...rest } = data

Working snippet

var data = {
  hello_en: 'hello world',
  'hello_zh-CN': '世界您好',
  something: 'nice day',
  something_else: 'isn\'t it'
}

const { hello_en, 'hello_zh-CN': hello_zHCN, ...rest } = data

console.log(hello_zHCN);


来源:https://stackoverflow.com/questions/44343763/es6-how-to-destructure-from-an-object-with-a-string-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!