0

I am trying to ForEach loop through data from a FireStore database and push it into an array. I am having some very strange issues though. The FireStore connection is irrelevant for now though, as I have taken to manually trying to make an array inside and outside a ForEach loop with the same array.push code, and the array built from inside the loop does not function correctly. It shows in Chrome as some sort of object/array with the length of 0 (yet still with content), while the exact same code built outside the ForEach block works fine. I am attach a screen shot that explains the issue.

Been racking my brain on this for hours, so any help is appreciated.

var HTRequirementsArray  =  [];
 var ReqArray  = [];

  db.collection('requirements').get().then((snapshot) => {
    snapshot.docs.forEach(doc => {

      HTRequirementsArray.push(["1",  "2", "3"]);      

    })
  })

ReqArray.push(["1",  "2", "3"]);
ReqArray.push(["1",  "2", "3"]);
ReqArray.push(["1",  "2", "3"]);

Code Snip

HTRequirementsArray does not work correctly.

BadCoder
  • 73
  • 1
  • 7
  • Welcome to Stack Overflow, please post your code as text, not as an image. And make sure it's [mre]. – Mukyuu Feb 24 '20 at 04:42
  • Please post the snippet of the code you have tried – Abana Clara Feb 24 '20 at 04:42
  • Please provide minimal working example. – Juhil Somaiya Feb 24 '20 at 04:43
  • All the code from `ReqArray.push(["1", "2", "3"]);` onwards is ran before your `HTRequirementsArray` is populated with data. Using `console.log` doesn't print a snapshot of the state of the current object, but rather a reference. To get a "snapshot" using `console.log(JSON.stringify(HTRequirementsArray)` to see what it actually contains – Nick Parsons Feb 24 '20 at 04:49
  • @NickParsons I have been trying to input HTRequirementsArray into DataTables which accepts arrays and it only shows up as blank data; however, ReqArray works fine. This isn't only a console log issue. Am I missing something? – BadCoder Feb 24 '20 at 04:51
  • `HTRequirementsArray` will only be populated when the `.then()` function runs, which most likely runs _after_ all your other code has ran. So, in order to access your populated version of `HTRequirementsArray` you'll need to work with it inside of the `.then()` callback function, not outside of it – Nick Parsons Feb 24 '20 at 04:54

0 Answers0