如何使用包含连字符的键将对象重构为变量? [英] How to destructure an object with a key containing a hyphen into a variable?

查看:90
本文介绍了如何使用包含连字符的键将对象重构为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:

  {
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 ,
最后修改:星期一,2016年06月06日06:14:57 GMT,
x-powered by:Express
}

现在得到内容类型 x使用结构化从对象中获取价值?

解决方案

就像你不能声明一个变量用连字符,你不能直接重组到一个。您将需要将变量重命名为别的东西,以便在当前范围内访问它。您可以使用以下解构语法:



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


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"

这篇关于如何使用包含连字符的键将对象重构为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆