Convert object of objects to array in JavaScript


Let’s say we have the following object of objects that contains rating of some Indian players, we need to convert this into an array of objects with each object having two properties namely name and rating where name holds the player name and rating holds the rating object −

Following is our sample object −

const playerRating = {
   'V Kohli':{
      batting: 99,
      fielding: 99
   },
   'R Sharma':{
      batting: 98,
      fielding: 95
   },
   'S Dhawan':{
      batting: 92,
      fielding: 90
   }
}

The solution to this is quite simple and straightforward, we will use the Object.keys() method to iterate over the object simultaneously converting it into an array like this.

Following is the complete code with output

Example

const playerRating = {
   'V Kohli':{
         batting: 99,
      fielding: 99
   },
   'R Sharma':{
      batting: 98,
      fielding: 95
   },
   'S Dhawan':{
      batting: 92,
      fielding: 90
   }
}
const objArray = [];
Object.keys(playerRating).forEach(key => objArray.push({
   name: key,
   rating: playerRating[key]
}));
console.log(objArray);

Output

[
   { name: 'V Kohli', rating: { batting: 99, fielding: 99 } },
   { name: 'R Sharma', rating: { batting: 98, fielding: 95 } },
   { name: 'S Dhawan', rating: { batting: 92, fielding: 90 } }
]

Updated on: 18-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements