I am working with firebase and javascript. I am trying to return one array from firebase-database after executing a query from two tables. When I console.log my data I get a separate array and object for each bit of data.
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);
});
});
This logs two separate arrays and objects: [{"text":"How are you","chatId":"chatId"}] [{"text":"Hi friend","chatId":"chatId2"}]
My desired result is [{"text": "How are you","chatId":"chatId"}, {"text":"Hi friend","chatId":"chatId2"}]
This is my data structure: data structure
How can I achieve my desired result? Thanks
just use apply.push to join as many arrays as you want. However, you might want to move your items = []; array outside the function. That's what is causing your problem. You are emptying the array every time you push/function fires.
var ar1 = [{ "text": "How are you", "chatId": "chatId" }]; var ar2 = [{ "text": "Hi friend", "chatId": "chatId2" }]; ar1.push.apply(ar1, ar2); console.log(ar1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.