user3737841
user3737841

Reputation: 665

How to retrieve data from Firebase?

I'm having a little trouble retrieving data from firebase in a specific format, though it seems it should be simple.

The database endpoint containers this data in this format:

{
    "A": {
        "width": 120,
        "height": 130
    },
    "B": {
        "width": 350,
        "height": 240
    },
    "C": {
        "width": 680,
        "height": 160
}

All I want to do is concat the letters with their respective width and height, then push all of the groups into an array and set that equal to 'data' so I can call 'data' anywhere in the program to use it, like so:

    var data = [{
    "id" : "A",
    "width": 120,
    "height": 130
}, {
    "id" : "B",
    "width": 350,
    "height": 240
}, {
    "id" : "C",
    "width": 680,
    "height": 160
}];

   // somewhere else in the file
  // data[0].end === 150

What's the simplest way to do this?

Thanks!

Upvotes: 1

Views: 125

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

Given that you're retrieving data from Firebase, you'll get it in a so-called DataSnapshot. That class has a convenient forEach() method on it, to allow iterating over its children:

snapshot.forEach(function(child) {
    data.push({
        name: child.key(),
        end: child.val().width,
        start: child.val().height
    });
})

I took the logic for start and end from Pamblam's answer, because I don't understand how that is meant to work.

Upvotes: 0

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

Here's a fiddle.

var junk = {
    "A": {
        "width": 120,
        "height": 130
    },
    "B": {
        "width": 350,
        "height": 240
    },
    "C": {
        "width": 680,
        "height": 160
        }
};
var data = [];
for (var property in junk) {
    if (junk.hasOwnProperty(property)) {
        data.push({
            name:property,
            end: junk[property].width,
            start:junk[property].height
        });
    }
}
console.log(data);

Upvotes: 2

Related Questions