Skip to content
javascript

How to convert an array to object in JavaScript

Jul 3, 2022Abhishek EH3 Min Read
How to convert an array to object in JavaScript

In this article, we will see different methods of converting an array into an object in JavaScript.

Using Object.assign()

We can use the Object.assign() function to convert array to object.

1const fruits = ["Apple", "Orange", "Banana", "Grapes"]
2const obj = Object.assign({}, fruits)
3console.log(obj) // 👉️ {0: 'Apple', 1: 'Orange', 2: 'Banana', 3: 'Grapes'}

As you can see the first parameter is an empty object and the second parameter is the array to be converted. The index of the array will be used as the key in the resulting object.

Using spread operator

You can use the ES6 spread operator to convert the array to an object as well:

1const fruits = ["Apple", "Orange", "Banana", "Grapes"]
2const obj = { ...fruits }
3console.log(obj) // 👉️ {0: 'Apple', 1: 'Orange', 2: 'Banana', 3: 'Grapes'}

The resulting object will be same structure as that of Object.assign() method.

Using Loops

You can use for loop to iterate over the array and push the items to the object one by one.

1const fruits = ["Apple", "Orange", "Banana", "Grapes"]
2const obj = {}
3for (let i = 0; i < fruits.length; i++) {
4 const fruit = fruits[i]
5 obj["key" + i] = fruit
6}
7console.log(obj) // 👉️ {key0: 'Apple', key1: 'Orange', key2: 'Banana', key3: 'Grapes'}

Alternatively, you can use forEach loop to achieve the same:

1const fruits = ["Apple", "Orange", "Banana", "Grapes"]
2const obj = {}
3fruits.forEach((fruit, index) => (obj["key" + index] = fruit))
4
5console.log(obj) // 👉️ {key0: 'Apple', key1: 'Orange', key2: 'Banana', key3: 'Grapes'}

Using reduce function

You can use the reduce function provided by the array to convert it to an object.

1const fruits = ["Apple", "Orange", "Banana", "Grapes"]
2const obj = fruits.reduce((accumulatedObj, currentValue, index) => {
3 accumulatedObj[index] = currentValue
4 return accumulatedObj
5}, {})
6
7console.log(obj) // 👉️ {0: 'Apple', 1: 'Orange', 2: 'Banana', 3: 'Grapes'}

The reduce function runs for every item in the array and we add the current value to the accumulated object in each iteration.

Using Object.fromEntries

If you have a 2-dimensional array with the key in the first index and value in the second index, you can use Object.fromEntries function to convert it to an object as shown below.

1const person = [
2 ["name", "John"],
3 ["age", 30],
4]
5const obj = Object.fromEntries(person)
6console.log(obj) // 👉️ {name: 'John', age: 30}

These are the few methods that can be used to convert an array to an object in JavaScript. If you know of any other types, comment them down below.

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2022 CodingDeft.Com