【问题标题】:How to loop through the data I receive from snapshot.val() and push it to an array based on keys如何遍历从 snapshot.val() 收到的数据并根据键将其推送到数组
【发布时间】:2018-02-18 23:57:32
【问题描述】:

我想根据用户键循环从snapshot.val() 收到的数据并将它们推送到一个数组中。我尝试在这样的 for..in 循环的帮助下做到这一点,

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

但我得到了这样的东西,

如果您注意到,我的第一个数组在用户键下包含 1 个对象,而我的第二个数组在其用户键下包含 3 个对象。如何将每个值推送到单独的数组中?

任何帮助将不胜感激!谢谢

【问题讨论】:

  • 新数组中键的每一个值,你为什么想要那个?
  • 不,我不是这个意思,抱歉。如果您看到我的控制台快照,我的 intVal 中有 4 个对象,并且每个数组都有多个对象嵌套在其键中。来自 db 的值在这里有点重复。我想将 db 中的每个对象作为一个数组推送到其随机用户密钥下。因此,就我而言,我期望的结果应该有 4 个数组,其中一个对象作为其子对象,没有任何重复数据。再次抱歉不简洁!
  • 这里让我感兴趣的是你为什么要得到随机数据。无法在您的功能中处理? .这感觉像是一种解决方法

标签: javascript angular firebase ionic-framework ionic3


【解决方案1】:

有一个DataSnapshot.forEach() method 正是为此目的:

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】:

您可以为每个对象再次迭代数据

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】:

    尚未测试此代码,但应该符合您的需要。

    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】:

      仅仅使用数组映射就可以解决我认为的所有问题。

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

      【讨论】:

        猜你喜欢
        • 2021-02-03
        • 2022-11-14
        • 2013-01-19
        • 1970-01-01
        • 2020-09-16
        • 1970-01-01
        • 2011-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多