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

↘锁芯ラ 提交于 2019-12-22 01:33:14

问题


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?


回答1:


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"


来源:https://stackoverflow.com/questions/39825868/how-to-destructure-an-object-with-a-key-containing-a-hyphen-into-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!