【问题标题】:Get sum of data in several firebase nodes获取多个firebase节点中的数据总和
【发布时间】:2017-10-12 10:07:55
【问题描述】:

我正在开发一个 ionic 2 应用程序。 我在firebase中有这种数据

我需要的是通过 exams 节点并获得所有分数的总和。 在 firebase 文档中有这样的例子。

var query = firebase.database().ref("users").orderByKey();
query.once("value")
  .then(function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      // key will be "ada" the first time and "alan" the second time
      var key = childSnapshot.key;
      // childData will be the actual contents of the child
      var childData = childSnapshot.val();
  });
});

但我不知道如何在我的情况下使用它。 谁能帮帮我??

谢谢

【问题讨论】:

    标签: angular typescript firebase-realtime-database ionic2


    【解决方案1】:

    你的json结构不对,重新配置实现如下

    exams : [ { name: '50' , marks :50 },
               { name: 'exam1' , marks :60 }
    
            ]
    

    通过这个你可以循环并计算所有标记的总和

    【讨论】:

    • 感谢您的快速回复。这是我添加新考试和标记的代码。但是如果我要像您的回答一样单独添加标记。它只会覆盖所有其他数据。 Addexams(userid){ let exams={ examid:this.examno, marks:this.marks } return new Promise((reslove)=>{ this.userProfile.child(userid).set({exams}); reslove(true); }); } @Aravind @aravind
    • 我没听懂你。详细说明
    【解决方案2】:

    您可以在lodash 中轻松做到这一点

    >_ npm install --save lodash
    

    import { forEach,sum} from 'lodash';
    
    ...
    
    let marks:[];
    forEach(this.exam,value => {
      marks.push(value.mark);
    });
    console.log(sum(marks));
    

    Sum

    【讨论】:

    • Thnx 的idea。肯定需要使用和检查。Thnx
    猜你喜欢
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2020-05-05
    • 2017-03-26
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多