Convert Array to Object in JavaScript

  1. Use the object.assign() Method to Convert an Array to an Object in JavaScript
  2. Use the array.reduce() Method to Convert an Array to an Object in JavaScript
  3. Use the Spread Operator to Convert an Array to an Object in JavaScript

Arrays and Objects are considered very important in JavaScript. Both are mutable and can store some values in JavaScript.

We use arrays when we store multiple values in a single variable, while an object can hold multiple variables with their values.

Generally, it is faster to use objects while having large amounts of data.

In this tutorial, we will learn how to convert an array to an object in JavaScript.

Use the object.assign() Method to Convert an Array to an Object in JavaScript

The assign() method can iteratively read properties from one or more than one object to a target object. It returns the target object.

Check the code below.

const array = ['foo', 'boo', 'zoo'];
const obj = Object.assign({}, array);
console.log(obj)

Output:

{0: "foo", 1: "boo", 2: "zoo"}

Use the array.reduce() Method to Convert an Array to an Object in JavaScript

The reduce() method can apply a function (that you provide) on each element in an array. It returns a single output value.

We can use it to make the necessary conversion.

For example,

const array = ['foo', 'boo', 'zoo']
array.reduce(function(target, key, index) {
  target[index] = key;
  return target;
}, {}) //initial empty object

Output:

{0: "foo", 1: "boo", 2: "zoo"}

Use the Spread Operator to Convert an Array to an Object in JavaScript

In JavaScript, the spread operator (...) can unpack all the array elements. We can use it to convert an array to an object.

For example,

const arr = ["foo", "boo", "zoo"];
const obj = {...arr};
console.log(obj);

Output:

{0: "foo", 1: "boo", 2: "zoo"}
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Array

  • Store Key-Value Array in JavaScript
  • JavaScript Declare Empty Array
  • Related Article - JavaScript Object

  • Filter Object in JavaScript