Search code examples
javascriptdestructuringecmascript-2016ecmascript-next

Destructure array to object property keys


I have an array of values like:

const arr = [1,2,3];

Is there any way I can use destructuring to create the following output? If not, what is the easiest way I can do this in ES6 (or later)?

const obj = {
    one: 1,
    two: 2,
    three: 3
};

I tried this, but I guess it doesn't work as this is the syntax for computed keys:

const arr = [1,2,3];
const obj = {
  [one, two, three] = arr
};

Solution

  • I don't believe there's any structuring/destructuring solution to doing that in a single step, no. I wanted something similar in this question. The old := strawman proposal doesn't seem to have legs in the new proposal list, so I don't think there's much activity around this right now.

    IMHO, this answer is the best one here (much better than this one). Two steps, but concise and simple.

    But if it's two steps, you could also use a simple object initializer:

    const arr = [1,2,3];
    const obj = {
      one: arr[0],
      two: arr[1],
      three: arr[2]
    };
    console.log(obj);

    Another option is to do it with several temporary arrays but technically only one statement (I am not advocating this, just noting it):

    const arr = [1,2,3];
    const obj = Object.fromEntries(
        ["one", "two", "three"].map((name, index) =>
            [name, arr[index]]
        )
    );
    console.log(obj);