Convert Array to Object

David Hellsing picture David Hellsing · Nov 18, 2010 · Viewed 916.3k times · Source

What is the best way to convert:

['a','b','c']

to:

{
  0: 'a',
  1: 'b',
  2: 'c'
}

Answer

Oriol picture Oriol · Apr 3, 2016

ECMAScript 6 introduces the easily polyfillable Object.assign:

The Object.assign() 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.

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

The own length property of the array is not copied because it isn't enumerable.

Also, you can use ES6 spread syntax to achieve the same result:

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