Home » vue » Array of JSON object is not empty but cannot iterate with foreach, show zero length [duplicate]

Array of JSON object is not empty but cannot iterate with foreach, show zero length [duplicate]

Posted by: admin November 26, 2021 Leave a comment

Questions:

I read a collection about book checkout from firestore in create().

The data is store in checkout array that declared in data().

export default {
  name: "checkout-history",
  data() {
    return {
      checkout: []
      ]
    };
  },
  created() {
    db.collection("checkout")
        .get()
        .then(querySnapshot => {
          querySnapshot.forEach(doc => {
            const data = {
              id: doc.id, // firebase document id
              book_did: doc.data().book_did,
              borrowed_date: doc.data().borrowed_date,
              copies_did: doc.data().copies_did,
              due_date: doc.data().due_date
            };
            this.checkout.push(data); // push to array
          });
        });

      console.log(this.checkout)  // show data, as in the image below

      console.log(this.checkout.length)  // get 0
      console.log(Object.keys(this.checkout).length)  // get 0
      }
      ......

When I run console.log(this.checkout);, console show this:

enter image description here

However, I cannot iterate it, the console show this.checkout.length is 0

I also tried to use Object.keys but no luck.

Object.keys(this.checkout).forEach(key => {
     const keys = this.checkout[key];
     console.log(keys);
});

I really don’t know what to do anymore.

I read many answers online and tried most of them, but none of them work.

Answers: