我正在使用 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": "[email protected]"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "[email protected]"
},
// and more...
}
我想將此資料顯示為物件陣列。預期輸出示例
[
{
"name": "Jhon Doe",
"profile": "profilelink",
"email": "[email protected]"
},
{
"name": "Cr7",
"profile": "profilelink",
"email": "[email protected]"
}
// and more........ ^_~
]
任何幫助將不勝感激!并隨時提出與我的問題或問題有關的任何疑問!
謝謝 :)
uj5u.com熱心網友回復:
似乎您只需要字典中的值,您可以通過這種方式轉換資料:
const lst = {
"random-user-id-1": {
"name": "Jhon Doe",
"profile": "profilelink",
"email": "[email protected]"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "[email protected]"
},
}
const expectedFormatRes = Object.values(lst);
console.log(expectedFormatRes);
uj5u.com熱心網友回復:
吉爾的答案的替代方法是使用 Firebase 的內置。forEach手術:
if (snapshot.exists) {
let values = [];
snapshot.forEach((child) => {
value.push(child.val());
})
console.log(values);
}
雖然更長,但它的優點是它維護了資料庫回傳資料的順序,當您orderBy...在查詢中指定子句時,這變得相關。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455470.html
