1

I have a feeling that this is not possible, but maybe there is an obscure hack that I could learn to do the following:

// pseudocode
let x = ["num1", "str1"]
let y = [1337, "foo"]
let [x...] = y

// desired results => 
   num1 === 1337
   str1 === "foo"

In other words, initialize variables with names that come from an array. In the above, the variable "num1" would be assigned the value 1337.

The use case is: the length of x and y will always be the same; their order will always match; we cannot predict the content of either. Of course, I can simply for on x, and match the position to the content in y, but I'd like to see if I can be more declarative and match them programmatically.

Cœur
  • 37,241
  • 25
  • 195
  • 267
kuzyn
  • 1,905
  • 18
  • 30

1 Answers1

3

You can have the output as an object like so:

let x = ["number", "string"];
let y = [1337, "foo"];
const res = x.reduce((acc, curr, idx) => ({ ...acc, [curr]: y[idx] }), {});
console.log(res);

Or if you want a two-dimensional array:

let x = ["number", "string"];
let y = [1337, "foo"];
const res = x.map((e, i) => [e, y[i]]);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    This will not work because it create object and not variable, it will only work if you update `window` object but this is only if called from global scope. No other way unless you do some eval, but this will not use destructure same as with `window` update. – jcubic Jun 04 '19 at 09:28
  • What do you mean @jcubic? I don't understand... – Jack Bashford Jun 04 '19 at 09:29
  • 1
    The question was to create variable `string` and `number` not object with properties. The only way to create variables dynamically is window object or eval. – jcubic Jun 04 '19 at 09:29
  • 1
    Just checked duplicate question it seem that it's possible after all, but not like in your answer. – jcubic Jun 04 '19 at 09:33