Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through the data I receive from snapshot.val() and push it to an array based on keys

I want to loop through the data I receive from snapshot.val() based on user keys and push them into an array. I tried doing it with the help of for..in loop like this,

firebase.database().ref('\interests').child("I would like to dine with").on('value', (snapshot) => {
  var data = snapshot.val();
  if(snapshot.exists()){
    for(let key in data){
      console.log("data[key]",data[key]);
      this.intVal.push(data[key]);
      console.log("intVal",this.intVal);
    }
  }
})

But I'm getting something like this,

enter image description here

If you notice, my first array contains 1 object under a user key and my second array contains 3 objects under their user keys. How can I push every single value in a separate array?

Any help would be much appreciated! Thanks

like image 456
Gowtham Avatar asked Sep 10 '17 18:09

Gowtham


People also ask

What is data snapshot?

Data Snapshots allows you to capture and maintain historical data from a report. It periodically snapshots the data from a chosen report, and stores them in a table for historical report creation & analysis.

How to store data in firebase realtime database using react native?

To install the "app" module, view the Getting Started documentation. # Install & setup the app module yarn add @react-native-firebase/app # Install the database module yarn add @react-native-firebase/database # If you're developing your app using iOS, run this command cd ios/ && pod install && cd ..


1 Answers

There is a DataSnapshot.forEach() method precisely for this purpose:

firebase.database().ref('\interests').child("I would like to dine with").on('value', (snapshot) => {
  snapshot.forEach((child) => {
    console.log(child.key, child.val()); 
    this.intVal.push(child.val());
    console.log("intVal",this.intVal);
  });
  }
})
like image 116
Frank van Puffelen Avatar answered Nov 07 '22 19:11

Frank van Puffelen