Search code examples
typescriptecmascript-6destructuring

Object destructuring with property names that are not valid variable names


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


Solution

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

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