4

I have an object like this:

const myObject = { 'docs.count': 1000, uuid: 11244, 'pri.store.size': 2453 }

I would like to do a destructuring assignment. Is that only possible for this type of fields?

const { uuid } = myObject;

Thanks!

gaheinrichs
  • 565
  • 5
  • 13
  • While this may seem like an annoying question, why would you want this? And how would you reference a variable with a dot in it later, if it were possible? – Etheryte Oct 25 '17 at 20:15
  • Its useful to take only what you need out of an object and if the object has this kind of property names, I would like to know the limitations of the destructuring assignment. – gaheinrichs Oct 25 '17 at 20:18
  • Sorry if I wasn't clear, I understood that you wanted to do the same shorthand destruct for the dotted property. Seems I misunderstood you. – Etheryte Oct 25 '17 at 20:19

1 Answers1

12

Variable names can't include a dot, so you can't get do const docs.count = 1000, for example. Destructuring allows you to extract the values even if the property name can't be a the name of a variable, but you'll need to assign them a valid variable name:

const myObject = { 'docs.count': 1000, uuid: 11244, 'pri.store.size': 2453 }

const { 'docs.count': docsCount } = myObject;

console.log(docsCount);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Technically global variables can contain a dot: window["foo.bar"]=5; – user7951676 Oct 25 '17 at 20:38
  • 1
    They are properties of the `window` object. You can't call them as a standard variable `console.log(foo.bar);`, only as a property of the window object `console.log(window["foo.bar"])`. – Ori Drori Oct 25 '17 at 20:55