-1

I realize there is no way to get a dictionary of local variables in a javascript function, and no equivalent of python's locals(). However, is there a way to write a function that would assist in this. For example, something like:

var a = 1;
var b = 2;

var output = locals(a, b);
console.log(output);

And output would be a dictionary with all the variables:

{
    "a": 1,
    "b": 2
}

Or, any other way apart from me manually creating a map, and inserting each field.

rouble
  • 16,364
  • 16
  • 107
  • 102
  • Can you use array for this? – Ahmed Ali Nov 25 '19 at 18:32
  • https://stackoverflow.com/questions/17276206/list-all-js-global-variables-used-by-site-not-all-defined – epascarello Nov 25 '19 at 18:33
  • As the questions you link to say: No. JS provides no mechanisms for inspecting what variables exist (other than globals when they are added to the default object as a side-effect) – Quentin Nov 25 '19 at 18:35
  • 1
    If you are going to make a static function call, referencing the variables, you can use the short property syntax of the object literal: `const output = { a, b }` – Christian C. Salvadó Nov 25 '19 at 18:36
  • @Quentin, I am not asking to inspect the variables in scope. I understand that is not possible. I am asking if there is a way to create a helper method to assist with creating a dictionary of specified local variables. The method will be passed all the variables of interest. So, this question is not really a duplicate. – rouble Nov 25 '19 at 18:39
  • @CMS, thats pretty nifty. Thanks. – rouble Nov 25 '19 at 18:56

1 Answers1

4

No.

Since you can't pass variables (only values) the data passed to such a function would be 1 and 2 with no association with the variable name.

You can, however, use the shorthand object syntax:

const output = { a, b };

… where an identifier without a value will take its value from the variable of the same name.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335