How to Convert an Array to Object in JavaScript

To convert an array to an object in JavaScript, you can use the “Array.prototype.reduce()” method. The method reduces an array to a single value by passing a callback function on each array element.

Example 1

const mainArray = [
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']

const myObject = mainArray.reduce((obj, [key, value]) => {
  obj[key] = value;
  return obj;
}, {});



{ key1: 'value1', key2: 'value2', key3: 'value3' }

In the above code example, the mainArray is created with nested arrays, where the first element in each nested array is the key, and the second element is the value.

The reduce() method is called on mainArray with an initial value of an empty object {}.

The callback function of reduce() function takes two arguments: an accumulator object and the current nested array [key, value].

The callback function assigns the value of value to the property of obj with the key and returns the updated obj.

Finally, the reduce() method returns the completed myObject Object with the same key-value pairs as the mainArray.

Example 2

If the array only contains values (not key-value pairs), you can use the “Object.assign()” method to convert it to an object with numeric keys:

const mainArray = ['value1', 'value2', 'value3'];

const mainObject = Object.assign({}, mainArray);



{ '0': 'value1', '1': 'value2', '2': 'value3' }

In this code example, the Object.assign() method is called with an empty object {} as the first argument and mainArray as the second. This creates a new object with numeric keys corresponding to the indices of mainArray.

Leave a Comment