如何以正确的方式获取所有数据 firebase-real-time-database JavaScript
how to get all data in correct way firebase-real-time-database JavaScript
我正在使用 node.js 并且我正在从 firebase 实时数据库获取数据。问题是我得到的数据是这样的:
求数据获取码! JS
import firebaseApp from '../config.js';
import { getDatabase, ref, onValue } from "firebase/database";
const userRef = ref(database, "Users");
onValue(userRef, (snapshot) => {
if (snapshot.exists) {
const data = snapshot.val();
console.log(data); // data printed to console
}
}, {
onlyOnce: true
});
控制台输出
{
"random-user-id-1": {
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example@email.com"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "example@email.com"
},
// and more...
}
我想将此数据显示为对象数组。预期输出示例
[
{
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example@email.com"
},
{
"name": "Cr7",
"profile": "profilelink",
"email": "example@email.com"
}
// and more........ ^_~
]
我们将不胜感激任何帮助!并随时提出与我的问题或问题相关的任何疑问!
谢谢你:)
看来您只需要字典中的值,您可以这样转换数据:
const lst = {
"random-user-id-1": {
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example@email.com"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "example@email.com"
},
}
const expectedFormatRes = Object.values(lst);
console.log(expectedFormatRes);
Gil 的替代方案是使用 Firebase 的 built-in。 forEach
操作:
if (snapshot.exists) {
let values = [];
snapshot.forEach((child) => {
value.push(child.val());
})
console.log(values);
}
虽然时间更长,但它的优点是它维护了数据库返回数据的顺序,当您在查询中指定 orderBy...
子句时,这就变得相关了..
我正在使用 node.js 并且我正在从 firebase 实时数据库获取数据。问题是我得到的数据是这样的:
求数据获取码! JS
import firebaseApp from '../config.js';
import { getDatabase, ref, onValue } from "firebase/database";
const userRef = ref(database, "Users");
onValue(userRef, (snapshot) => {
if (snapshot.exists) {
const data = snapshot.val();
console.log(data); // data printed to console
}
}, {
onlyOnce: true
});
控制台输出
{
"random-user-id-1": {
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example@email.com"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "example@email.com"
},
// and more...
}
我想将此数据显示为对象数组。预期输出示例
[
{
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example@email.com"
},
{
"name": "Cr7",
"profile": "profilelink",
"email": "example@email.com"
}
// and more........ ^_~
]
我们将不胜感激任何帮助!并随时提出与我的问题或问题相关的任何疑问!
谢谢你:)
看来您只需要字典中的值,您可以这样转换数据:
const lst = {
"random-user-id-1": {
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example@email.com"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "example@email.com"
},
}
const expectedFormatRes = Object.values(lst);
console.log(expectedFormatRes);
Gil 的替代方案是使用 Firebase 的 built-in。 forEach
操作:
if (snapshot.exists) {
let values = [];
snapshot.forEach((child) => {
value.push(child.val());
})
console.log(values);
}
虽然时间更长,但它的优点是它维护了数据库返回数据的顺序,当您在查询中指定 orderBy...
子句时,这就变得相关了..