Convert A Firebase Database Snapshot/Collection To An Array In Javascript

Last updated: May 4, 2017

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.

Take the following example:

firebase.database().ref('/posts').on('value', function(snapshot) {
    console.log(snapshot.val());
});

Let’s imagine that we have 20 posts in our database. You’ll get back an object containing keys and objects for all of our imaginary posts.

If you’re working with a Javascript framework or library such as Aurelia, then you’ll know that iterating an object opposed to an array is more complicated (especially HTML templating).

So, here is a function I ended up writing which I use quite a lot in my Firebase applications:

function snapshotToArray(snapshot) {
    var returnArr = [];

    snapshot.forEach(function(childSnapshot) {
        var item = childSnapshot.val();
        item.key = childSnapshot.key;

        returnArr.push(item);
    });

    return returnArr;
};

If you’re a modern Javascript kind of developer, then you might appreciate a nicer to look at version of the above function:

export const snapshotToArray = snapshot => {
    let returnArr = [];

    snapshot.forEach(childSnapshot => {
        let item = childSnapshot.val(); 
        item.key = childSnapshot.key;
        returnArr.push(item);
    });

    return returnArr;
};

To use our newly created function

firebase.database().ref('/posts').on('value', function(snapshot) {
    console.log(snapshotToArray(snapshot));
});

Worth pointing out here is the key for our item in the database is added to our object using the property key if you need to access it later.

Purchase Aurelia for Real World Applications over at Leanpub now

 

Dwayne

 

8 thoughts on “Convert A Firebase Database Snapshot/Collection To An Array In Javascript

  1. An ES7 one-liner:

    let arr = Object.entries(snapshot).map(e => Object.assign(e[1], { key: e[0] }));

  2. That key interrupts the loop number, for example if a node only contain 2 child then another extra child ‘key’ is added. that increase the loop number.

  3. did you try it ?

    the problem in the first place is we get object of values…
    so we dont have .forEach … because its unknown object and not array !

Leave a Reply

Your email address will not be published. Required fields are marked *