Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure object properties with key names that are invalid variable names?

As object keys are strings they can contain any kind of characters and special characters. I recently stumbled upon an object which I receive from an API call. This object has '-' in it's key names.

const object = {
   "key-with-dash": []
}

Destructuring does not work in this case because key-with-dash is not a valid variable name.

const { key-with-dash } = object;

So one question came to my mind. How am I supposed to destructure the object in such cases? Is it even possible at all?

like image 743
larrydahooster Avatar asked Aug 04 '16 08:08

larrydahooster


People also ask

Can you Destructure an object?

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.

Can you Destructure array of objects?

Array DestructuringValues in arrays are destructured based on their index . The variable can be named anything you want, but the variable name associated with the index is how it is assigned. We can also assign values to variables that are already declared.

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

const data = {
   "key-with-dash": ["BAZ"]
}

const {"key-with-dash": foo} = data;

console.log("foo", foo);
like image 55
Hitmands Avatar answered Oct 19 '22 03:10

Hitmands


Just give it a valid name

let object = { 'key-with-dash': [] }
let {'key-with-dash':y} = object
console.log(y)
// => []

Did you also know you can destructure with variables?

let object = { 'key-with-dash': [] }
let key = 'key-with-dash'
let {[key]:y} = object
console.log(y)
// => []
like image 48
Mulan Avatar answered Oct 19 '22 02:10

Mulan