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

JavaScript调用API读取实时数据库JSON数据解析取值问题

Firebase实时数据库用户数据解析问题

数据库结构

实时数据库存储的users节点结构如下:
实时数据库结构截图

现有实现代码

当前编写的数据拉取代码如下:

get(child(dbref, 'users/')).then((snapshot) => {
  if (snapshot.exists()) {
    snapshot.forEach(function (childSnapshot) {
      const key = childSnapshot.key
      const childData = childSnapshot.val()
      console.log(childData, '62. line "childData" console')
      const user = {
        id: key,
        value: childData,
      }
      console.log(user, '68. line "user" console')
    })
  } else {
    console.log('No data available')
  }
})

实际运行输出

代码运行后控制台打印结果如下:
控制台输出截图

期望输出结构

需要正确解析拉取到的数据,拿到包含revenue、ip、location等字段的结构化用户信息,期望格式如下:

{
  [用户key]: {
    revenue: xxx,
    ip: xxx,
    location: xxx
  }
}

修复方案

  • 现有代码中childSnapshot.val()已经返回对应用户ID下的完整属性对象,本身就包含revenue、ip、location等字段,不需要额外嵌套到value属性中。控制台默认折叠打印对象,点击展开即可看到全部字段,不属于数据拉取失败。
  • 修正后可直接按期望结构组装数据,参考代码如下:
const userMap = {}
get(child(dbref, 'users/')).then((snapshot) => {
  if (snapshot.exists()) {
    snapshot.forEach(function (childSnapshot) {
      const userKey = childSnapshot.key
      const userRawData = childSnapshot.val()
      // 按目标结构组装
      userMap[userKey] = {
        revenue: userRawData.revenue,
        ip: userRawData.ip,
        location: userRawData.location
        // 如需保留该用户下其他字段,可追加 ...userRawData 展开
      }
    })
    // 全量数据组装完成后可在这里调用后续逻辑
    console.log('结构化用户数据:', userMap)
  } else {
    console.log('No data available')
  }
})

内容的提问来源于stack exchange,提问作者zanthez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:39:43