Here are five ways to convert an array to an object in JavaScript:
- Using spread operator
- Using Object.fromEntries()
- Using Object.assign()
- Using for loop
- Using Array.forEach()
Method 1: Using spread operator
The spread operator … is used to copy enumerable properties from one object to another. For arrays, the index will become the key.
Here is a code example:
const arr = ['a', 'b', 'c'];
const obj = { ...arr };
console.log(obj);
Output
{ '0': 'a', '1': 'b', '2': 'c' }
Method 2: Using Object.fromEntries()
The Object.fromEntries() method converts a list of key-value pairs into an object.
Here is a code example:
const arr = [['key1', 'value1'], ['key2', 'value2']];
const obj = Object.fromEntries(arr);
console.log(obj);
Output
{ key1: 'value1', key2: 'value2' }
Method 3: Using Object.assign()
Object.assign() method can copy the values of all enumerable properties from one or more source objects to a target object. It creates a new object by merging the properties of an array into an empty object.
Here is a code example:
const arr = ['a', 'b', 'c'];
const obj = Object.assign({}, arr);
console.log(obj);
Output
{ '0': 'a', '1': 'b', '2': 'c' }
Method 4: Using a for loop
You can use a for loop to iterate through the array and add each element to the object using the array index as the key.
Here is a code example:
const arr = ['a', 'b', 'c'];
let obj = {};
for (let i = 0; i < arr.length; i++) {
obj[i] = arr[i];
}
console.log(obj);
Output
{ '0': 'a', '1': 'b', '2': 'c' }
Method 5: Using Array.forEach()
You can also use the Array.forEach() method. Here is a code example:
const arr = ['a', 'b', 'c'];
let obj = {};
arr.forEach((value, index) => {
obj[index] = value;
});
console.log(obj);
Output
{ '0': 'a', '1': 'b', '2': 'c' }
Conclusion
For smaller arrays, readability and convenience might be more important, so using methods like Object.fromEntries(), Object.assign(), or the spread operator could be beneficial.
If your array consists of key-value pairs and you want to convert it to an object, Object.fromEntries() is the most semantically appropriate method.
By considering the size of your array and your specific needs, you can choose the method that best balances performance and readability.
Related posts
Convert Object to Array of Objects in JavaScript
Object to String in JavaScript
Flatten an Array of Objects in JavaScript

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.