I recently encountered a case where the database that I was using returned some data in the form of an object of objects and I wanted to convert it to an array of objects. Here’s how I went about it:
Suppose we have the following object of objects:
const usersObj = {
0: {
id: 1000,
firstname: "Ahmad",
lastname: "Bilal"
},
1: {
id: 1515,
firstname: "Adeela",
lastname: "Ayman"
},
2: {
id: 2550,
firstname: "Adel",
lastname: "Ameen"
}
}
In order to convert it to an array of objects, we will use map
:
const users = Object.keys(usersObj).map(key => usersObj[key]);
console.log(users);
/*[{
* firstname: "Ahmad",
* id: 1000,
* lastname: "Bilal"
*}, {
* firstname: "Adeela",
* id: 1515,
* lastname: "Ayman"
*}, {
* firstname: "Adel",
* id: 2550,
* lastname: "Ameen"
}]*/
We use Object.keys()
in order to select keys of each object (0,1,2) and chain map
onto it and pass the keys into the map through the parameter key
. We then take the usersObj
object and use the key
param as the index in order to extract the object as map
iterates through the object.