Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure an object with a key containing a hyphen into a variable? [duplicate]

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 nested object?

Nested Object and Array Destructuring Here's another example with an array of objects: You can destructure as deeply as you like: As you can see, keys a , b , and c are not implicitly defined, even though we pulled out nested values, firstElemOfC and remainingElementsOfC , from the array at c .

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.

Does object Destructuring make a copy?

No, destructuring will give you a reference. AFAIK, there is no way to configure a destructure to shallow clone at the same time.


Just like you cannot declare a variable with a hyphen, you can't destructure directly to one. You will need to rename your variable to something else in order to access it on the current scope. You can use the following destructuring syntax to do that:

const x = {
  "accept-ranges":"bytes",
  "cache-control":"public, max-age=0",
  "content-length":"1174",
  "content-type":"application/json",
  date:"Mon, 03 Oct 2016 06:45:03 GMT",
  etag:"W/496-157892e555b",
  "last-modified":"Mon, 03 Oct 2016 06:14:57 GMT",
  "x-powered-by":"Express"
};
const { "accept-ranges": acceptRanges } = x;
console.log(acceptRanges); // "bytes"