Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use special characters (like hyphen) in destructuring assignment syntax?

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

like image 525
TOPKAT Avatar asked Jan 01 '23 22:01

TOPKAT


2 Answers

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);
like image 86
zero298 Avatar answered Jan 03 '23 11:01

zero298


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)
like image 23
Maheer Ali Avatar answered Jan 03 '23 12:01

Maheer Ali