ES6 — How to destructure from an object with a str

2020-08-10 09:29发布

问题:

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);