web analytics

How to Convert an Array to Objects JAVASCRIPT ?

This article will discuss how to convert an array to objects in JavaScript. There are numerous ways that we can follow. Most methods involve using different inbuilt methods available in JavaScript, whereas a few require the developer to implement their custom logic. Before we get into the top 6 methods to convert an array to an object, let’s discuss objects and arrays a bit.

What are Objects and Array in the JavaScript?

Both Arrays and Objects are quite special elements in JavaScript. Objects are a unique data type that is mutable and used to store a collection of data rather than a single value. An array is a common data type used to store a list of different values and multiple objects. The conversion of an array to an object in JavaScript is quite easy. Here is the complete list of methods that you can use.

Top 7 Methods to Convert an Array to Objects.

  1. Use Object.assign() Method

An Object.assign() method copies all the values from the enumerable properties of one object to another object(also known as the target object). The output of a function invocation will return a target object.

It takes two arguments:

  • The target object you want to convert to.
  • The source array

In the backend, this function will loop through all the elements in the array and create a new object with a key-value pair. Here, the key would be the index of the element in the array.

For an example,

Object.assign({}, [l, m, n,o]); 

The following code would convert [l, m, n, o] to

{0: "l", 1:"m", 2:"n", 3:"o"}

You can use this method in the ECMAScript 6 Version.

Use a custom method using the for loop.

function convertToObject(array) {
	var object = {};
	for(var i = 0 ; i< array.length; i++){
		Object[i] = array[i];
}
return object;

}
  1. For loop

This is the second method that you can use to convert an array to an objects in JavaScript. Here we will use a for loop that will iterate through all the array elements and add them as a key-value pair to the custom object. You can also use some other loops like do while and while loop instead of for loop.

[ "Alice", "Bob", "Sam", "George] 

and this would result to:

{ 
0 : "Alice",
1: "Bob",
2: "Sam",
3: "George",
}
  1. Reduce()

This is the third method you can use to convert an array to an object. The reduce() method will execute a method for every item in the array and store its value in an object entity. Developers can call reduce() method seamlessly on the array object. The following is the pseudocode for using this method.

const array = ["Amy", "Billy", "Steve"] 
const newObject = array.reduce(function(outcome, item, index) 
{ outcome[index] = item 
return outcome }, 
{}) 

// newObject = { "0": "Amy", "1": "Billy", "2": "Steve" }

We have created a function with three arguments, outcome, item, and index. The outcome is the final object created after conversion. The item is the element in the array, such as Amy, Billy, and Steve, and the index is the element’s position in the array.

  1. forEach Method

If you need to convert an array to an object in JavaScript using forEach, you need to follow certain steps. The steps are as follows.

  • Declare and initialize a variable and set it to an empty object
  • Use the forEach method to loop over the different elements in the array
  • Once the iteration is completed, add the elements to the object as a key-value pair.

Here is the pseudocode for insights.

const array_list = ["bat, 'ball', 'gun'];

const object = {};

arr.forEach((element, index) => {
  object['ele' + index] = element;
});

// {'ele0': 'bat', 'ele1': 'ball', 'ele2': 'gun'}
console.log(object);
  1. Convert an Array to an Object by using the forEach Method

If you need to convert an array to an object in JavaScript using forEach, you need to follow certain steps. The steps are as follows.

  • Declare and initialize a variable and set it to an empty object
  • Use the forEach method to loop over the different elements in the array
  • Once the iteration is completed, add the elements to the object as a key-value pair.

Here is the pseudocode for insights.

const array_list = ["bat, 'ball', 'gun'];

const object = {};

arr.forEach((element, index) => {
  object['ele' + index] = element;
});

// {'ele0': 'bat', 'ele1': 'ball', 'ele2': 'gun'}
console.log(object);
  1. Use Spread for conversion of an array to an object.

The JavaScript programming language has a spread method. The syntax of this is (…). You can use this to convert an array by simply using a one-line code.

`const obj = {...arr}`

Here, the spread will unpack all the elements of the array into an object, and all the indices of the elements will be converted to the object’s key to the values.

const array = ["a", "j", "k";

const object = {...array};
console.log(object); 
  1. Use Object.fromEntries to convert an Array to the object.

With this other method, you can convert an array to key-value pairs and put them in the object. To use this method, you need to pass the array as a function argument to the Object.FromEntries method. A short example is given below.

const array = [
	['name' : 'Alice'],
	['email' : 'alice@mail.com']

];

const object = Object.fromEntries(array);

console.log(object); // {name: 'alice', email: "alice@email.com}

How to convert an Array of objects to one single object in JS?

In the above examples, we have seen 1-D and 2-D arrays and converted them to objects. Here, we will discuss one important example where there are different objects in the array, and you want to convert them to an object. Here is a small pseudocode which will help you.

var arr = [{key:"00", value:"george"},{key:"11", value:"alex"}]; 
var object = arr.reduce( (obj, item) => Object.assign(obj, { [item.key]: item.value }), {}); 

console.log(object)

Here we have used a reduce method and Object.assign() to convert the array of objects to one single object. We take the key and assign a value to it in the new object that returns the following output.

object = {"00" : "george", "11" : "alex"}

The importance of converting an array to an object in JavaScript.

If you are a backend developer and would like to get the requests from the client, there is a certain format that most of the APIs follow, and it is known as the JSON format, or the JavaScript Object Notation. The API would require you to send a request body as an object.

Summary

The conversion of an array to an object in JavaScript is simple and can be easily done with only a few lines of code.  The common step for all the methods is iterating and storing the array of elements. With the help of this article, I hope you will have understood the different ways to convert an array to an object in JavaScript.