如何使用无效变量名的键名解构对象属性? [英] How to destructure object properties with key names that are invalid variable names?
本文介绍了如何使用无效变量名的键名解构对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于对象键是字符串,它们可以包含任何类型的字符和特殊字符.我最近偶然发现了一个从 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屋!
查看全文