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

时间:2022-05-18 23:14:38

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.

有谁知道你是否可以在属性名称中使用带空格的对象解构?也许这不可能完成,我意识到JavaScript表示法不正确,但我无法更改服务器json响应。

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'...

如果这是不可能的话,如果我可以使用某种语法(例如'as')分配变量,这将是很好的...

var {'my name' as name, age} = obj2; //name='Mr Jones';

Thanks

谢谢

2 个解决方案

#1


14  

You can assign it a valid variable name using this syntax:

您可以使用以下语法为其分配有效的变量名称:

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

// use myName here

#2


6  

When I have an object with spaces in the property name can I use object destructuring or not?

当我在属性名称中有一个带空格的对象时,我可以使用对象解构吗?

Yes, you can use destructuring, but you can always only assign to identifiers (variable names). As those don't allow spaces, you cannot use the shorthand syntax where property name and identifier are the same.

是的,您可以使用解构,但您始终只能分配标识符(变量名称)。由于那些不允许空格,您不能使用属性名称和标识符相同的简写语法。

It would be nice if I could assign the variable with some sort of syntax like 'as':

如果我可以使用某种语法(例如'as')分配变量,那将是很好的:

var {'my name' as name, age} = obj2;

as is for module imports/exports. For normal objects - both literals and destructuring - you use the colon ::

与模块导入/导出一样。对于普通对象 - 文字和解构 - 你使用冒号::

var {'my name': name, age} = obj2;

#1


14  

You can assign it a valid variable name using this syntax:

您可以使用以下语法为其分配有效的变量名称:

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

// use myName here

#2


6  

When I have an object with spaces in the property name can I use object destructuring or not?

当我在属性名称中有一个带空格的对象时,我可以使用对象解构吗?

Yes, you can use destructuring, but you can always only assign to identifiers (variable names). As those don't allow spaces, you cannot use the shorthand syntax where property name and identifier are the same.

是的,您可以使用解构,但您始终只能分配标识符(变量名称)。由于那些不允许空格,您不能使用属性名称和标识符相同的简写语法。

It would be nice if I could assign the variable with some sort of syntax like 'as':

如果我可以使用某种语法(例如'as')分配变量,那将是很好的:

var {'my name' as name, age} = obj2;

as is for module imports/exports. For normal objects - both literals and destructuring - you use the colon ::

与模块导入/导出一样。对于普通对象 - 文字和解构 - 你使用冒号::

var {'my name': name, age} = obj2;