How to loop through the data I receive from snapsh

2020-07-02 12:53发布

问题:

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,

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

回答1:

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


回答2:

You can iterate over data again for each object

for(let key in data){
     console.log("data[key]",data[key]);
     for(innerKey in data[key]){
       var obj = {};
       obj[innerKey]=data[key][innerKey];
       this.intVal.push(obj);
     }
     console.log("intVal",this.intVal);
}


回答3:

Have not tested this code yet but should fit your need.

var interest = data.pop();//remove the interest
var uniq = data.reduce((unique, users) => {
    for (userId in users) {
        if (!userId in unique.IDs) {
            unique.IDs[userId] = users[userId];
            unique.usersList.push(users[userId]);
        }
    }
    return unique;
}, {IDs:{},usersList :[]});

console.log('interest is', interest);
console.log('uniq user ids', Object.keys(uniq.IDs));
console.log('uniq user list', uniq.usersList);


回答4:

Just using array map can solve all pain i think.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map