You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript统计Firebase实时数据库中Declined状态的嵌套donation数量并显示在输入框

解决方案

要统计嵌套结构中donationStatus为Declined的捐赠对象总数,需要遍历每个用户下的捐赠节点进行筛选计数,具体修改代码如下:

var output1 = document.getElementById('output1');
const dbRef = ref(getDatabase(), 'Users');

// 获取所有用户数据
get(dbRef).then((snapshotData) => {
    let declinedCount = 0;

    // 遍历每个用户节点
    snapshotData.forEach((userSnapshot) => {
        const userData = userSnapshot.val();
        // 检查当前用户是否有donations节点
        if (userData.donations) {
            // 遍历该用户下的所有捐赠对象
            Object.values(userData.donations).forEach((donation) => {
                // 判断捐赠状态是否为Declined
                if (donation.donationStatus === 'Declined') {
                    declinedCount++;
                }
            });
        }
    });

    // 将统计结果显示到输入框
    output1.value = declinedCount;
    console.log('Declined捐赠总数:', declinedCount);
}).catch((error) => {
    console.error('数据获取失败:', error);
});

关键说明

  • 由于Firebase实时数据库无法直接跨层级查询所有用户下的捐赠状态,因此需要先获取所有用户数据,再逐层遍历用户的donations子节点。
  • 增加了空值判断(if (userData.donations)),避免用户没有捐赠数据时出现报错。
  • 把原代码中重名的output1参数改为snapshotData,避免DOM元素变量和Promise返回值冲突。

内容的提问来源于stack exchange,提问作者Jemina Marie Tagadtad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:20:50