How to convert an array to object in javascript?

featured Image

Here, in this article, we will learn how to convert an array to an object using JavaScript.

Converting between arrays and objects is a common task in JavaScript. There are many cases where you may have data in an array and need to convert it into an object representation, or vice versa.

In JavaScript, there are a few different ways to approach the task of converting an array to an object. The goal is to end up with an object where the array elements become object property values, using the array indices or other values as the keys.

This article will demonstrate different methods including:

1. Using Object.assign() method

2. Using spread operators

3. Using the reduce() function.

Now let’s see how to use the above functions and operators to convert an array to an object.

Convert an array to an object in JavaScript.

We will do the conversion from an array to an Object by the following solutions below.

Method 1: Using Object.assign() method

Object.assign() provides a simple way to copy values from an array into a new object instance.

let Arr = ['a','b','c'];
const objArr = Object.assign({}, Arr);
console.log(objArr)

Output :

{ '0': 'a', '1': 'b', '2': 'c' }

The Object.assign() method copies enumerable own properties from one or more source objects to a target object. We pass an empty object {} as the target, and the array as the source. This will copy the array elements as properties into the empty object.

The keys will be the array indices and the values will be the array elements.

Some key points:

  • Object.assign() modifies the target object, so we pass an empty object as the target to avoid mutating other objects.
  • It only copies enumerable and own properties from the source objects to the target object.
  • You can pass multiple source objects to merge them into the target object.

Method 2: Using Spread Operator

We can also convert an array to an object using the spread operator in JavaScript.

let Arr = ['a','b','c'];
const spread = { ...Arr }
console.log(spread)

Output:

{ '0': 'a', '1': 'b', '2': 'c' }

The spread syntax spreads out the elements of the array as the properties of the new object.

Here we create a new object {...array}, which copies the array elements into the object properties.

The rest of the behavior is similar to Object.assign():

  • The indices become keys and values become the elements.
  • It creates a shallow clone of the array as an object.
  • The target object is not mutated.

The spread syntax gives us a short and concise way to copy an array into a new object.

It lets you convert a JavaScript array to an object of the same keys/values. The spread syntax might be preferable then Object.assign() since it creates a new object without mutating the existing one.

Method 3: With the Custom key using reduce() method

let arr = ['a', 'b', 'c'];

let obj = arr.reduce((a, v) => ({...a, [v]: v}), {}); 

console.log(obj); // {a: 'a', b: 'b', c: 'c'}

Here we are:

  • Initializing the accumulator a to an empty object {}.
  • Spreading the accumulator a into a new object on each iteration: {...a}
  • Adding the new key-value pair: [v]: v
  • Returning the new object back as the accumulator.

So on each iteration, we make a new accumulated object with the spread syntax, rather than mutating the original. This avoids mutating the accumulator object directly.

Thus, combining the spread syntax with reduce() gives us a concise way to convert an array into an object without mutating the original. The spread syntax handles creating a new object on each iteration.

Summary

Here is a summary of the 3 methods to convert an array to an object in JavaScript:

Object.assign()

  • Creates a new object without mutating the original array or target object.
  • Concise syntax but requires passing an empty target object.
  • Copies properties from sources to target. Can merge multiple sources.

Spread syntax

  • Creates a new object without mutating array or other objects.
  • Very concise syntax.
  • Spread operator copies properties from array to new object.

Array.reduce()

  • Loops through array just once.
  • Can mutate initial accumulator object if you’re not careful.
  • Builds up object dynamically across iterations.
  • More explicit than other solutions.

Thus we can say that:

  • Object.assign() and spread syntax are best for simple conversion without mutations.
  • Reduce may be better if you need more flexibility in the conversion logic.
  • Spread syntax is very concise but may not be supported in old browsers.
  • All options create a shallow clone of the array as an object.

That’s it, these three are the easiest ways to convert your array to an object using JavaScript.


Related Topics:

Convert Javascript Array To Object Of Same Keys/Values

How to remove a property from an object in JavaScript?

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more