我正在使用 firebase 和 javascript。我试图在从两个表执行查询后从 firebase-database 返回一个数组。当我console.log我的数据时,我为每一位数据得到一个单独的数组和对象。
var userId = 'hirerId';
var chatIdRef = firebase.database().ref("members");
var chatsRef = firebase.database().ref("chats");
chatIdRef.child(userId).on('child_added', snap => {
chatsRef.child(snap.key).once('value', snap => {
items = [];
items.push({
text: snap.val().text,
chatId: snap.key
});
console.log(items);
});
});
这会记录两个单独的数组和对象:[{"text":"How are you","chatId":"chatId"}] [{"text":"Hifriend","chatId": “chatId2”}]
我想要的结果是[{"text": "How are you","chatId":"chatId"}, {"text":"Hifriend","chatId":"chatId2"}]
这是我的数据结构: data structure
怎样才能达到我想要的结果?谢谢
最佳答案
只需使用 apply.push 即可加入任意数量的数组。但是,您可能想移动您的元素= [];函数外部的数组。这就是导致你的问题的原因。每次按下/函数触发时,您都会清空数组。
var ar1 = [{
"text": "How are you",
"chatId": "chatId"
}];
var ar2 = [{
"text": "Hi friend",
"chatId": "chatId2"
}];
ar1.push.apply(ar1, ar2);
console.log(ar1);
关于javascript - 如何从 firebase-database 数据列表返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44709515/