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 :)
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With