JavaScript Converting array of objects into object of arrays

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have the following data about a team arranged in an array of objects, our task is to convert this data into an object with key as role and value as array of player names.

Our sample array −

const team = [{
   role: 'Batsman',
   player: 'V Kohli'
}, {
   role: 'Wicket Keeper',
   player: 'KL Rahul'
}, {
   role: 'Batsman',
   player: 'R Sharma'
}, {
   role: 'Wicket Keeper',
   player: 'R Pant'
}, {
   role: 'Bowler',
   player: 'B Kumar'
}, {
   role: 'Bowler',
   player: 'M Shami'
}, ]

Let’s define a function objectify() that takes in the array as an argument and returns the corresponding object.

The code for this will be −

const objectify = (team) => {
   const teamObject = {};
   team.forEach(member => {
      if(teamObject[member.role]){
         teamObject[member.role].push(member.player);
      }else{
         teamObject[member.role] = [member.player];
      }
   });
   return teamObject;
}
console.log(objectify(team));

Here, we loop over each array item one by one, if it exists in the teamObject we push the player into its value otherwise we assign it an array with the single player

Here’s the complete code −

Example

const team = [{
   role: 'Batsman',
   player: 'V Kohli'
}, {
   role: 'Wicket Keeper',
   player: 'KL Rahul'
}, {
   role: 'Batsman',
   player: 'R Sharma'
}, {
   role: 'Wicket Keeper',
   player: 'R Pant'
}, {
   role: 'Bowler',
   player: 'B Kumar'
}, {
   role: 'Bowler',
   player: 'M Shami'
}, ]
   const objectify = (team) => {
      const teamObject = {};
      team.forEach(member => {
         if(teamObject[member.role]){
            teamObject[member.role].push(member.player);
         }else{
            teamObject[member.role] = [member.player];
      }
   });
   return teamObject;
}
console.log(objectify(team));

Output

The output for this code in the console will be −

{
   Batsman: [ 'V Kohli', 'R Sharma' ],
   WicketKeeper: [ 'KL Rahul', 'R Pant' ],
   Bowler: [ 'B Kumar', 'M Shami' ]
}
raja
Published on 19-Aug-2020 10:05:20
Advertisements