How to destructure an object with a key containing a hyphen into a variable?

JavascriptEcmascript 6Destructuring

Javascript Problem Overview


How do I destructure a property from an object where the key contains a hyphen?

Eg:

{
  accept-ranges:"bytes",
  cache-control:"public, max-age=0",
  content-length:"1174",
  content-type:"application/json",
  date:"Mon, 03 Oct 2016 06:45:03 GMT",
  etag:"W/"496-157892e555b"",
  last-modified:"Mon, 03 Oct 2016 06:14:57 GMT",
  x-powered-by:"Express"
}

Now to get the content-type and x-powered-by values from the object using destructuring?

Javascript Solutions


Solution 1 - Javascript

Just like you cannot declare a variable with a hyphen, you can't destructure directly to one. You will need to rename your variable to something else in order to access it on the current scope. You can use the following destructuring syntax to do that:

const x = {
  "accept-ranges":"bytes",
  "cache-control":"public, max-age=0",
  "content-length":"1174",
  "content-type":"application/json",
  date:"Mon, 03 Oct 2016 06:45:03 GMT",
  etag:"W/496-157892e555b",
  "last-modified":"Mon, 03 Oct 2016 06:14:57 GMT",
  "x-powered-by":"Express"
};
const { "accept-ranges": acceptRanges } = x;
console.log(acceptRanges); // "bytes"

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
QuestionSathishView Question on Stackoverflow
Solution 1 - JavascriptCodingIntrigueView Answer on Stackoverflow