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

时间:2016-10-03 06:46:26

标签: javascript ecmascript-6 destructuring

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

例如:

{
  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"
}

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

1 个答案:

答案 0 :(得分:24)

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

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"