使用不是有效变量名称的属性名进行对象解构

使用不是有效变量名称的属性名进行对象解构(Object destructuring with property names that are not valid variable names)
JavaScript IT屋 2017/8/3 19:48:36

百度翻译此文 有道翻译此文
问 题

Does anyone know if you can use object destructuring with spaces in the property name? Maybe this cannot be done and I realize the JavaScript notation is incorrect but I cannot change the server json response.

var obj1 = {name: ‘Mr Smith’, age: 21};
//destructure
var {name, age} = obj1;
//name=‘Mr Smith’ and age=21
This works as expected.

But when I have the following object structure can I use object destructuring or not?

var obj2 = {“my name”: “Mr Jones”, age: 22};
var {‘my name’, age} = obj2;
If this is not possible It would be nice if I could assign the variable with some sort of syntax like ‘as’…

var {‘my name’ as name, age} = obj2; //name=‘Mr Jones’;
Thanks

解决方案
You can assign it a valid variable name using this syntax:

var {“my name”: myName, age} = obj2;

// use myName here
本文地址:IT屋 » Object destructuring with property names that are not valid variable names

问 题
有没有人知道您是否可以使用属性名称中的空格对象解构?也许这不能完成,我意识到JavaScript符号是不正确的,但我不能更改服务器json响应。

var obj1 = {名字:史密斯先生,年龄:21岁;
// destructure
var {name,age} = obj1;
// name ='史密斯先生和年龄= 21

这样可以预期。

但是当我有以下对象结构可以使用对象解构吗?

code> var obj2 = {我的名字”:琼斯先生”,年龄:22};
var {‘my name’,age} = obj2;

如果这是不可能的,如果我可以使用某种类型的语法’as’…

var {'my name’as name,age} = obj2; // name =‘琼斯先生’;

谢谢

解决方案
您可以使用以下语法为其分配一个有效的变量名:

var {my name”:myName, age} = obj2;

//使用myName这里

你可能感兴趣的:(JavaScript)