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
相关产品推荐
相关产品推荐

