Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of items from Firebase snapshot

I'm trying to get an array of items from my Firebase database, using a snapshot generated on page load. I've added the value of each object to an array, and now I'm trying to push an item from each object into another array with a for loop.

But when I create the second array, there are more items in it than there are objects in the snapshot.

I'm wondering how I can get around this. Any help would be awesome. Thanks.

Code:

var ref = firebase.database().ref().child('/scenes/' + projId).orderByChild('wordcount');
ref.once('value',function(snap) {
    snap.forEach(function(item) {
        var itemVal = item.val();
        keys.push(itemVal);
        for (i=0; i < keys.length; i++) {
            counts.push(keys[i].wordcount);
        }
    });
});
like image 926
SyrupandSass Avatar asked Jan 02 '17 13:01

SyrupandSass


People also ask

How to store arrays in Firebase?

Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names. However, to help people that are storing arrays in Firebase, when you call .val () or use the REST api to read data, if the data looks like an array, Firebase will render it as an array.

How do I retrieve data stored in Cloud Firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.

What is Firebase Realtime Database?

Because Firebase is a NoSQL JSON data store, you might have noticed that when you get some data from Firebase that it is an object. If the title wasn’t obvious enough, we are talking about using Firebase Realtime Database in a web application. Let’s imagine that we have 20 posts in our database.

Is there a getlist() method in documentsnapshot?

But as DocumentSnapshot contains different flavors for the get () method, according to each data type, getString (), getLong (), getDate (), etc, it would have been very helpful if we also had a getList () method, but unfortunately we don’t. So something like this: It’s not possible. So how can we still get a List<User>?


1 Answers

Each time you add something to keys you loop over them all again. You should probably move it outside your forEach:

var ref = firebase.database().ref().child('/scenes/' + projId).orderByChild('wordcount');
ref.once('value',function(snap) {
    snap.forEach(function(item) {
        var itemVal = item.val();
        keys.push(itemVal);
    });
    for (i=0; i < keys.length; i++) {
        counts.push(keys[i].wordcount);
    }   
});
like image 68
Mathew Berg Avatar answered Oct 26 '22 06:10

Mathew Berg