larrydahooster larrydahooster - 7 months ago 48
Javascript Question

How to destructure object properties with key names that are invalid variable names?

As object keys are strings they can contain any kind of characters and special characters. I recently stumbled upon an object which I receive from an API call. This object has '-' in it's key names.

const object = {
"key-with-dash": []

Destructuring does not work in this case because
is not a valid variable name.

const { key-with-dash } = object;

So one question came to my mind. How am I supposed to destructure the object in such cases? Is it even possible at all?


const data = {
   "key-with-dash": ["BAZ"]

const {"key-with-dash": foo} = data;

console.log("foo", foo);