Search code examples
javascriptarraysecmascript-6destructuring

Destructure an array programmatically in JS


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.


Solution

  • 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; }