2017-06-22 20 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