Convert Array to Object

Created by OriolLinked to 88.1m issues across 189 teams

tl;dr

Here's how to convert an array into an object using ECMAScript 6, ES8 spread syntax, and reduce.

ECMAScript 6 introduces the easily polyfillable Object.assign() method.

"This method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object."

To convert an array into an object using Object.assign(), you can use the following syntax:

Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}

Note, that the own length property of the array is not copied because it isn't enumerable. You can also use ES8 spread syntax on objects to achieve the same result. To do this, use the following syntax:

{ ...['a', 'b', 'c'] }

Finally, you can use reduce to create custom keys. To do this, use the following syntax:

['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {}) // { a: "a", b: "b", c: "c" }