1

Let's imagine that I have two files. File number one is called obj.js and looks like this:

const obj = {
  item1: 'some text',
  item2: 'some other text',
  item3: 'more text'
  ...
  item99: `yet more text`
}

export default obj

File number 2 looks is called main.js and looks like this:

import obj from './obj.js'

Now, here is my question. In file number two (main.js) I can access properties off of the obj Object like this: obj.item2. What I want to know is can I destructure this object so that I can access any of the properties as follows: item2, item26, item38, etc (i.e., without the need to preface it with obj.)?

If so, any idea how?

I'm not trying to import any particular property, but rather want the option of using whichever properties I chose to without the need to reference obj.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Moshe
  • 6,011
  • 16
  • 60
  • 112
  • 3
    `import { item2 } from "./obj";`? – jonrsharpe Apr 14 '19 at 12:54
  • @jonrsharpe Thanks for your help. With that said, clarified my question. I'm not trying to destructure a particular property, but rather all the properties so that I can use whichever property I want. I'd also like to do this without having to list each property by name. – Moshe Apr 14 '19 at 13:03
  • that doesn't make sense, then you'd have a load of names just magically appear in your local scope with no easy way for people to see what they are. – jonrsharpe Apr 14 '19 at 13:15
  • @jonrsharpe I'm just would like to know if this is possible and, if so, how. The example I gave is just there to illustrate what I'm trying to figure out -- not my particular use cases. Be well, Moshe :) – Moshe Apr 15 '19 at 10:51
  • Just `import { names, you, want } from "wherever";`. Importing all of them risks conflicts and makes the code harder to follow. – jonrsharpe Apr 15 '19 at 10:53

1 Answers1

-1

You question is simply that how can you destructure all the properties of object. Actually its dynamic variables names in other words which are not possible. But here you want to declare them in global scope its possible using global and dynamic properties names.

import obj from './obj.js'
Object.keys(obj).forEach(x => global[x] = obj[x]);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • What if I have a large object with many different items that I want to destructure. Is there a way to destructure all the items without listing them all by name? – Moshe Apr 14 '19 at 13:01
  • @Moshe I got it. You can do that with some limitations I have updated the answer – Maheer Ali Apr 14 '19 at 13:07