如何使用包含连字符的键将对象解构为变量?

Sat*_*ish 21 javascript destructuring ecmascript-6

如何从键包含连字符的对象中构造属性?

例如:

{
  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"
}
Run Code Online (Sandbox Code Playgroud)

现在使用解构来从对象获取content-typex-powered-by值?

Cod*_*gue 32

就像你不能用连字符声明变量一样,你不能直接解构为一个.您需要将变量重命名为其他内容才能在当前范围内访问它.您可以使用以下解构语法来执行此操作:

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"
Run Code Online (Sandbox Code Playgroud)