[英]how to get all data in correct way firebase-real-time-database JavaScript
I am using node.js and I am getting data from firebase real-time database.我正在使用 node.js,我正在从 firebase 实时数据库获取数据。 The problem is I am getting data something like this:问题是我得到的数据是这样的:
for data getting code!获取数据的代码! JS 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
});
Console Output控制台 Output
{
"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...
}
I want to display this data as an array of objects.我想将此数据显示为对象数组。 Example of expected output预期示例 output
[
{
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example@email.com"
},
{
"name": "Cr7",
"profile": "profilelink",
"email": "example@email.com"
}
// and more........ ^_~
]
thank you:)谢谢你:)
seems like you need only the values from your dict, you can transform your data this way:似乎你只需要字典中的值,你可以这样转换你的数据:
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);
An alternative to Gil's answer would be to use Firebase's built-in.吉尔回答的另一种选择是使用 Firebase 的内置功能。 forEach
operation: forEach
操作:
if (snapshot.exists) {
let values = [];
snapshot.forEach((child) => {
value.push(child.val());
})
console.log(values);
}
While longer, this has the advantage that it maintains the order in which the database returned the data, which becomes relevant when you specify an orderBy...
clause on your query..虽然时间更长,但它的优点是它维护了数据库返回数据的顺序,当您在查询中指定orderBy...
子句时,这就变得相关了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.