如何使用无效变量名称的键名称来重构对象属性? [英] How to destructure object properties with key names that are invalid variable names?

查看:171
本文介绍了如何使用无效变量名称的键名称来重构对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As object keys are strings they can contain any kind of characters and special characters. I recently stumbled upon an object which I receive from an API call. This object has '-' in it's key names.

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

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

Destructuring does not work in this case because key-with-dash is not a valid variable name.

const { key-with-dash } = object;

所以有一个问题来了。在这种情况下,我应该如何破坏对象?是否有可能?

So one question came to my mind. How am I supposed to destructure the object in such cases? Is it even possible at all?

推荐答案

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

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

console.log("foo", foo);

这篇关于如何使用无效变量名称的键名称来重构对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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