0

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) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
1
  • Why don't you create an empty array first and push each item in the array inside the "pipe" method? Commented Apr 13, 2019 at 4:22

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.