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?
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"