我使用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........ ^_~
]
任何帮助我们都将不胜感激!请随时询问与我的问题或问题有关的任何疑问
谢谢:(
您似乎只需要dict中的值,您可以通过以下方式转换数据:
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的内置。forEach
操作:
if (snapshot.exists) {
let values = [];
snapshot.forEach((child) => {
value.push(child.val());
})
console.log(values);
}
虽然时间更长,但它的优点是它保持了数据库返回数据的顺序,当您在查询中指定orderBy...
子句时,这一顺序就变得相关了。。