Object destructuring with property names that are not valid variable names

前端 未结 2 772
轻奢々
轻奢々 2020-11-27 07:31

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 can

相关标签:
2条回答
  • 2020-11-27 07:50

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

    var {"my name": myName, age} = obj2; 
    
    // use myName here
    
    0 讨论(0)
  • 2020-11-27 08:03

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

    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;
    
    0 讨论(0)
提交回复
热议问题