2

I understand this is a very dumb question, I am dumb, maybe confused.

Let us say that I have a module foo.js that after doing works returns an object like this bellow,

return {something, anotherThing, yetAnotherThing};

Now, I want to get those in my bar.js and work with, but not with all of them. Maybe sometimes with something and sometimes with anotherThing etc. So, what I do is,

const foo = require('../foo.js')
const { something } = foo()

Then I work with something in my files.

The problem here is, most of the time, I need something or anotherThing on a random basis. Like I do not know which one I will need. Sometimes I need all of them and somethings I need only one or two.

So, is it possible to write a function that dynamically gets the destructed variables and work with them? For example, if I create an array of the things needed from the foo file and pass that array to a function that takes element from the array to get variable from foo.js and work with it? An incorrect code example of what I am saying will be,

const iAmWrong = ( arr) => {
  
    for (let i = 0; i < arr.length; i++) {
        const { arr[i] } = foo();
    }

    arr[i]();
};

There must be a way to achieve this right? Maybe not how I am thinking it is in code but I hope it is not impossible.

Please help.

user1
  • 37
  • 3
  • 6
    If your code is this dynamic and undecidable, then the last thing you want is *dynamic destructuring*. That's basically *variable variables*, which basically never makes sense either. Just don't destructure, and dynamically access the object's properties like `obj[prop]` instead. – deceze May 27 '21 at 10:04
  • Can you please give me any code sample? – user1 May 27 '21 at 10:05
  • 3
    Of something that's not possible? No. – deceze May 27 '21 at 10:05
  • I see reference to another question, I will check that, thank you for marking that. – user1 May 27 '21 at 10:06
  • Also relevant: [“Variable” variables in JavaScript](https://stackoverflow.com/q/5187530) – VLAZ May 27 '21 at 10:07
  • 2
    "*Sometimes I need all of them and somethings I need only one or two.*" - so just destructure to create variables for all of them, so that you have them available if you need them. No harm done with unused variable values. – Bergi May 27 '21 at 10:11

0 Answers0