Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 724
keano Avatar asked Apr 12 '16 15:04

keano


People also ask

Can you Destructure array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

How do you Destructure an object in react?

In destructuring, It does not change an array or any object, it makes a copy of the desired object or array element by assigning them in its own new variables, later we can use this new variable in React (class or functional) components. It makes the code more clear.

What is Destructure property?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

How do you Destructure an object in ES6?

When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.


2 Answers

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; 
like image 22
Bergi Avatar answered Sep 28 '22 02:09

Bergi


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

var {"my name": myName, age} = obj2;   // use myName here 
like image 124
David Sherret Avatar answered Sep 28 '22 02:09

David Sherret