Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to Object

What is the best way to convert:

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

to:

{   0: 'a',   1: 'b',   2: 'c' } 
like image 651
David Hellsing Avatar asked Nov 18 '10 14:11

David Hellsing


People also ask

How do you convert an array to an object in Java?

Converting an array to Set object The Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.

How do you convert a list of objects into an object?

The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.

How do you convert an object array into a single object?

assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.


1 Answers

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 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" } 
like image 180
Oriol Avatar answered Nov 09 '22 11:11

Oriol