0

I have a collection in Firestore with the following structure:

Publications   
     PubData <---- This is a Doc
        1892872 <---- This is a map  
          Name: abc
          Id: 123 
        1892875 <---- This is a map  
          Name: abc
          Id: 123 

Querying the PubData document:

fb.publicationsCollection
  .doc("pubdata")
  .get()
  .then(res => {
   let pubData = res.data();
   })

returns the following data:

{1892872: {…}, 1892875: {…}}

How can I return this as an array, so I can iterate over it with a for loop?

ogot
  • 341
  • 2
  • 17

2 Answers2

2

You can iterate an object's properties with a foreach loop:

const pubData = res.data();
Object.keys(pubData).forEach(function(key) {
  // key is 1892872, pubData[key] is the associated object
  console.log(key, pubData[key]);
});

Since you didn't really say what exactly you wanted the array to contain, I'll leave it up to you to figure out how the keys and values of the document's map should be represented in that final array.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
2

Since you asked for an array of entries, you can use Object.entries:

fb.publicationsCollection
  .doc("pubdata")
  .get()
  .then(res => {
    let pubData = Object.entries(res.data());
    // pubData will look like:
    // [["1892872", {…}], ["1892875", {…}]]
   })
Scott Rudiger
  • 1,224
  • 12
  • 16