2017-06-22 22 views
0

我正在使用firebase和javascript。我試圖從兩個表執行查詢後從firebase-database返回一個數組。當我console.log我的數據我得到一個單獨的數組和對象的每一位數據。如何從firebase-database中返回一個數組列表

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":"Hi friend","chatId":"chatId2"}]

我期望的結果是[{"text": "How are you","chatId":"chatId"}, {"text":"Hi friend","chatId":"chatId2"}]

這是我的數據結構: data structure

我怎樣才能實現我想要的結果?謝謝

+0

看看'Array.concat()' –

回答

0

只是使用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);

+0

謝謝。移動功能之外的項目= []。 – Neil