5 Ways to Convert an Array to an Object in JavaScript

Updated: March 19, 2023 By: Goodman Post a comment

In JavaScript, an array is a collection of items, while an object is a collection of key-value pairs. Sometimes, it can be useful to convert an array to an object to make it easier to access specific items. This practical, example-based article will show you some different ways to do so.

Using the Spread Operator

You can use the spread operator to create a new object by spreading the elements of the array into an empty object.

Example:

const arr = ["Sling", "Academy", "JavaScript", "Tutorial"];
const obj = {...arr};
console.log(obj);

Output:

{0: 'Sling', 1: 'Academy', 2: 'JavaScript', 3: 'Tutorial'}

In my opinion, this approach is elegant and neat. Each property of the newly created object will have the value of an element of the array, and the key is the index of that element in the array.

Using the Object.fromEntries() method

You can use the Object.fromEntries() method to create an object from an array of key-value pairs (a two-dimensional array or a 2D array).

Example:

const props = [
  ['name', 'Sling Academy'],
  ['color', 'green'],
  ['age', 5],
];

const obj = Object.fromEntries(props);
console.log(obj);

Output:

{ name: 'Sling Academy', color: 'green', age: 5 }

See also: Create an Object from Arrays of Keys and Values.

Using the Object.assign() method

You can use the Object.assign() method to create a new object by merging the properties of an array into an empty object.

Example:

const arr = ['A', 'B', 'C', 'D'];
const obj = Object.assign({}, arr);
console.log(obj);

Output:

{0: 'A', 1: 'B', 2: 'C', 3: 'D'}

Using a For loop

Example:

const arrayToObject = (arr) => {
  let obj = {};
  for (let i = 0; i < arr.length; i++) {
    obj[i] = arr[i];
  }
  return obj;
};

const arr = ['A', 'B', 'C', 'D'];
const obj = arrayToObject(arr);
console.log(obj);

Output:

{0: 'A', 1: 'B', 2: 'C', 3: 'D'}

Using the Array.forEach() method

Example:

const names = ['Ranni the Witch', 'Fire Giant', 'Takuro', 'Pipi'];
const obj = {};
names.forEach((elem, i) => {
  obj[i] = elem;
});
console.log(obj); 

Output:

{0: 'Ranni the Witch', 1: 'Fire Giant', 2: 'Takuro', 3: 'Pipi'}

Final Words

You’ve explored more than one technique to turn a given array into an object in modern JavaScript. Which approach you will go with in your next program? Please let us know by leaving a comment. Happy coding & have a nice day!