如何用无效变量名称的键名解构对象属性?

由于对象键是字符串,因此它们可以包含任何类型的字符和特殊字符。我最近偶然发现了一个从 API 调用中接收到的对象。这个对象的键名中有’-’。

const object = {
"key-with-dash": []
}

在这种情况下,解构不起作用,因为 key-with-dash不是一个有效的变量名。

const { key-with-dash } = object;

我突然想到一个问题。在这种情况下,我该如何破坏物体呢?这有可能吗?

24287 次浏览

const data = {
"key-with-dash": ["BAZ"]
}


const {"key-with-dash": foo} = data;


console.log("foo", foo);

Just give it a valid name

let object = { 'key-with-dash': [] }
let {'key-with-dash':y} = object
console.log(y)
// => []

Did you also know you can destructure with variables?

let object = { 'key-with-dash': [] }
let key = 'key-with-dash'
let {[key]:y} = object
console.log(y)
// => []

Hello Fellow Developers, I have found a break through this error if none of the above work.

  1. Follow this code

    <i>const anyVar = yourData["data-example"] </i>
    
  2. Hope this works for you if you have any questions please make to ask me.

P.S: I know its a old question but I faced a issue so I thought that some people may also face this. So that is why I have posted this.