4

I'm curious of why that seems impossible:

const {a, b, 'special-one'} = { a:1, b:2, 'special-one': 3 };
// output => missing : after property id

Will it be possible to find that syntax working in future ES versions ?

Thanks for your lights :)

adiga
  • 34,372
  • 9
  • 61
  • 83
TOPKAT
  • 6,667
  • 2
  • 44
  • 72
  • 1
    This is impossible because '-' is a special character, and this in case, an operator at that. – Tim VN Jun 05 '19 at 13:42
  • 1
    `special-one` is not a valid variable name. You couldn't access this variable afterwards. You'll need to alias it at least. – deceze Jun 05 '19 at 13:42
  • 1
    Nit-pick: this isn't "spread syntax", it's "destructuring assignment". You might want to update the question title. – zero298 Jun 05 '19 at 14:14

2 Answers2

7

Rename the variable within the destructure statement, you can't have a variable with a hyphen in it's name. You can rename using the syntax below, see MDN: Assigning to new variable names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

const {
  a,
  b,
  'special-one': specialOne
} = {
  a: 1,
  b: 2,
  'special-one': 3
};

console.log(specialOne);
zero298
  • 25,467
  • 10
  • 75
  • 100
  • 1
    The rules for allowed variable names can be found [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables). – 3limin4t0r Jun 05 '19 at 13:55
3

special-one can't be the variable name. So you need another name for that like specialOne. Use : after the key name for new variable name.

const {a, b, 'special-one':specialOne} = { a:1, b:2, 'special-one': 3 };
console.log(specialOne)

In the above case you have a plain string as key name. But if there is an expression you will need to use []

let keyName = 'special-one'

const {a, b, [keyName]:specialOne} = { a:1, b:2, 'special-one': 3 };
console.log(specialOne)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73