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

JavascriptEcmascript 6Destructuring

Javascript Problem Overview


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;

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

Javascript Solutions


Solution 1 - Javascript

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

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

console.log("foo", foo);

Solution 2 - Javascript

Just give it a valid name

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

Did you also know you can destructure with variables?

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

Solution 3 - Javascript

Hello Fellow Developers, I have found a break through this error if none of the above work.

  1. Follow this code

    <i>const anyVar = yourData["data-example"] </i>
    
  2. Hope this works for you if you have any questions please make to ask me.

P.S: I know its a old question but I faced a issue so I thought that some people may also face this. So that is why I have posted this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlarrydahoosterView Question on Stackoverflow
Solution 1 - JavascriptHitmandsView Answer on Stackoverflow
Solution 2 - JavascriptMulanView Answer on Stackoverflow
Solution 3 - JavascriptShehroze MalikView Answer on Stackoverflow