35

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
keano
  • 691
  • 7
  • 9
  • Possible duplicate of [ES6 object destructuring and changing target variable](https://stackoverflow.com/q/34904523/1048572) – Bergi Jun 17 '17 at 11:15

2 Answers2

45

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

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

// use myName here
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • Great! thanks, didn't realise you could change the property name like that. Although it does state that in the typescript docs, so should have checked there first! My bad.. https://www.typescriptlang.org/docs/handbook/variable-declarations.html – keano Apr 12 '16 at 15:42
  • 1
    @keano the [documentation at mdm](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) is pretty good too. At least in the future someone will be able to find it easily here. – David Sherret Apr 12 '16 at 15:45
9

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;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I've used the 'as' keyword for importing modules I thought there was some sort of similar syntax when destructuring objects... thanks for the explanation though :) – keano Apr 12 '16 at 19:13
  • Interesting, never knew this! Pity there's no way to dynamically destructure an object, similar to PHP's `extract()`, or is there? – Ifedi Okonkwo Dec 15 '16 at 07:43
  • @IfediOkonkwo Dynamic variable names are a pita. And actually JS [has them](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) - but you really don't want to use this. Better use computed property names and destructure into known variables. – Bergi Dec 15 '16 at 08:10