Open In App

JavaScript - Convert an Array to an Object

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
4 Likes
Like
Report

These are the following ways to convert an array to an Object:

1. Using JavaScript Object.assign() method

The first approach is using the Object.assign() method. This method copies the values of all enumerable properties from source objects(one or more) to a target object.


Output
{"0":1,"1":2,"2":3,"3":4}

2. Using JavaScript for loop

In this method, we will traverse the array using a JavaScript for loop and assign each array element to the target object.


Output
{"0":"GFG1","1":"GFG2","2":"GFG3","3":"GFG4"}

3. Using JavaScript Object.fromEntries() method

The Object.fromEntries() method in JavaScript is a standard built-in object which is used to transform a list of key-value pairs into an object. This method returns a new object whose properties are given by the entries of the iterable.


Output
{ JS: 'JavaScript', GFG: 'GeeksforGeeks' }

4. Using the Spread Operator

The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array. 


Output
{ '0': 'Geeks', '1': 'for', '2': 'Geeks' }

5. Using forEach

Using the forEach method iterates over the array of key-value pairs. For each pair, the key is used as the object property, and the corresponding value is assigned. This approach dynamically builds an object from the array elements.


Output
{ '0': 'Geeks', '1': 'for', '2': 'Geeks' }

6. Using JavaScript reduce Method

The reduce method applies a function against an accumulator and each element in the array to reduce it to a single value. In this case, we use it to accumulate an object from the array elements.


Output
{"0":"Hello","1":"World","2":"Welcome","3":"To","4":"JavaScript"}

Next Article

Similar Reads