snippetjavascriptCritical
How to convert an array into an object?
Viewed 0 times
arrayobjecthowconvertinto
Problem
What is the best way to convert:
to:
['a','b','c']to:
{
0: 'a',
1: 'b',
2: 'c'
}Solution
ECMAScript 6 introduces the easily polyfillable
The
enumerable own properties from one or more source objects to a target
object. It will return the target object.
The own
Also, you can use ES8 spread syntax on objects to achieve the same result:
For custom keys you can use reduce:
Object.assign:The
Object.assign() method is used to copy the values of allenumerable 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 ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }For custom keys you can use reduce:
['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }Code Snippets
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}{ ...['a', 'b', 'c'] }['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }Context
Stack Overflow Q#4215737, score: 1061
Revisions (0)
No revisions yet.