Converting array of objects to an object in JavaScript


The given there is an array and the task is to convert an array of objects to an object.

Input-Output Scenario

Let’s look into an input-output scenario of converting the array objects into an object. Consider there is an array having objects in it. Now, we need to convert those array objects into a single JSON object.

Const Arr = [ {1:'one'}, {2:'two'} ]; Output = { "1":"one", "2":"two" }; //Object

Using Object.assign()

The Object.assign() method is an in-built property in JavaScript which copies all the own enumerable properties from one or more objects to a target object.

Syntax

Following is the syntax of Object.assign(),

Object.assign(target, ...src)

where,

  • target is an object where the values and properties have to be copied. This target object will be returned after modification.

  • src is the source object containing the properties that have to be copied.

This Object.assign() method will return the target object.

Example

In the example below, we have created an array with an object in it. Then we used Object.assign() method and passed an empty object as a target object. Then by using spread(…) operator we can expand all the elements of an object as a series of values. We’ve copied the array objects into the empty object.

<!DOCTYPE html> <html> <head> <title>Converting array of objects to an object</title </head> <body> <button onClick="func()"> Click to convert</button> <p id = "para"></p> <script> function func(){ const Cricket = [ { Team: 'India' }, { Captain: 'Virat kohli' }, { Age: 34 } ]; const obj = Object.assign({}, ...Cricket); document.getElementById("para").innerHTML = JSON.stringify(obj); }; </script> </body> </html>

In the output, we have copied all the array object properties to the target object which is an empty object.

Using map() method

The map() method will create a new array by calling a function for each array element, it calls a function only once for each element in the array. The original array will not be modified.

Syntax

Following is the syntax of map() method in JavaScript.

map((ele) => { /* … */ })

where,

  • ele is the current element that is being processed in the array.

The map() method will return every element which is the result of a callback function in a new array.

Example

In the example below, we have an array of objects. In the map() method we have passed (item) as a parameter which will be processed in the array and we have passed a function to the map() method which will return the properties in the form of an array (as map() method return the output in array).

So, to convert this array of objects we use the object.assign() method. By using the spread(…) operator we extract all the elements of the output of the map() method and copied them to the target object (empty object).

<!DOCTYPE html> <html> <title>Convert an array of objects to an object</title> <head> <button onClick="func()"> Click to convert</button> <p id = "para"></p> <script> const players = [ {name:'Dhoni',team:'India'}, {name:'Dilshan',team:'Srilanka'}, {name:'Daniel sams',team:'Australia'}, {name:'Dinesh karthik',team:'India'} ]; function func(){ var res = players.map(item => ({ [item.name]: item.team }) ); var obj = Object.assign({}, ...res ); document.getElementById("para").innerHTML = JSON.stringify(obj); }; </script> </head> </html>

As we can see in the ouput, the array of objects has converted into an object.

Example

for loop

In this example below, we have an array of objects. We have run a for loop and iterating through the array. The loop will assign the name and team into empty object till it assigns all the properties. Then we print the empty object and will get the name – team pair as an object.

<!DOCTYPE html> <html> <head> <title>Convert an array of objects to an object</title> </head> <body> <button onClick="func()"> Button </button> <p id = "para"> </p> <script> function func(){ var batsmen = [ {name : 'Virat', team : 'India'}, {name : 'Ponting', team : 'Australia'}, {name : 'Kallis', team : 'South Africa'} ]; var obj = {}; let x = 0; let len = batsmen.length; for (x; x < len; x++) { obj[batsmen[x].name] = batsmen[x].team; } document.getElementById("para").innerHTML = JSON.stringify(obj); }; </script> </body> </html>

In the output, we have converted the array of objects into an object with the help of for loop and an empty object.

Updated on: 23-Sep-2022

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements