Reputation:
I have a Cloud Firestore document that is supposed to be an array of objects. It looks like this
docname: {
0: {...}
1: {...}
2: {...}
This is expected, because I populated that document like this
myDocRef.set( {...user.myArray});
The problem I have is when I go to retrieve the data from the document. I currently do it like this
getUserItems(uid) {
return this._db.doc<MyObj>(`users/${uid}/mysubcollection/items`).valueChanges();
}
That returns an object of objects and I need it to be an array of objects so that I can use forEach()
on it.
I tried using the map()
operator but its giving me some results I am not understanding.
So, my goal is to convert that object of objects to an array of objects and I tried this
items$.pipe(
tap(item => console.log('before map', item )),
map(item => [item]),
tap(item => console.log('after map', item ))
)
.subscribe(...);
This does kind of work since it converts the object of objects to an array of objects but of course it puts all objects into the first dim of a two dim array to it looks like this
Array [Object(9)]
What can I do here to convert an object of objects to an array of objects so that my end result is like this
Array(9) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
So going from this
Object(9) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
to this
Array(9) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
Upvotes: 0
Views: 83
Reputation: 44107
If the order of the items in the array does not matter, you can just use Object.values
:
const objectOfObjects = {
0: { name: "Zero" },
1: { name: "One" },
2: { name: "Two" },
3: { name: "Three" }
};
const unorderedArray = Object.values(objectOfObjects);
console.log(unorderedArray);
If they do matter, get both the key and the value first using Object.entries
, then sort them in ascending order, and map
out the values:
const objectOfObjects = {
0: { name: "Zero" },
1: { name: "One" },
2: { name: "Two" },
3: { name: "Three" }
};
const orderedArray = Object.entries(objectOfObjects).sort(([a], [b]) => a - b).map(([, obj ]) => obj);
console.log(orderedArray);
Upvotes: 1