larrydahooster
larrydahooster

Reputation: 4163

How can I 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 key-with-dash is not a valid variable name.

const { key-with-dash } = object;

How am I supposed to destructure the object in such cases? Is it even possible at all?

Upvotes: 99

Views: 33317

Answers (3)

Mulan
Mulan

Reputation: 135415

Just give it a valid name:

let object = { 'key-with-dash': [] }
let {'key-with-dash':y} = object
console.log(y)
// => []

Or destructure using a variable:

let object = { 'key-with-dash': [] }
let key = 'key-with-dash'
let {[key]:y} = object
console.log(y)
// => []

Upvotes: 51

Shehroze Malik
Shehroze Malik

Reputation: 1

I have found a breakthrough for this error if none of the previous answers work.

Follow this code:

const anyVar = yourData["data-example"]

Upvotes: -7

Hitmands
Hitmands

Reputation: 14199

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

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

console.log("foo", foo);

Upvotes: 151

Related Questions