
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } } ]
Advertisements