31

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Dave Sag
  • 13,266
  • 14
  • 86
  • 134
  • 2
    See this [MDN section](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Invalid_JavaScript_identifier_as_a_property_name) – maazadeeb Jun 03 '17 at 12:16

1 Answers1

60

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);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 1
    Thanks very much. The answer seems so obvious once it's in front of me. :-) – Dave Sag Jun 03 '17 at 12:37
  • Yes, its looks like it, but its not, I have stuck with this myself for a long time too :) – Shubham Khatri Jun 03 '17 at 12:38
  • 1
    Extending topic starters' questions - is there a way to specify destructuring alias via text constant or any other way? For example, `const {'_abc_abc_': someAliasConstant} = someObject;` – lazy.lizard Oct 25 '20 at 16:09