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

安稳与你 提交于 2019-12-04 02:26:32

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

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!