Table of Contents
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] = fruit6}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))45console.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] = currentValue4 return accumulatedObj5}, {})67console.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.
Do follow me on twitter where I post developer insights more often!