Monday, 3 April 2017

Create an array of objects from Firebase of specified keys and values with forEach loop

I need to return a single array of objects from Firebase that I can then manipulate.

The code below logs many arrays of incrementing length. I only need the last array that has the total number of objects that I can make with the data available in the child I'm referencing. Once I have this array I need to manipulate it.

var array2 = [];

WEEKLYnights_Held.on("child_added", function(snapshot) {

  snapshot.forEach(function(data) {
    var WEEKosl = new Object();
    WEEKosl.days = data.key;
    WEEKosl.people = data.val();

    array2.push(WEEKosl)

    console.log(array2);
});
  });

So I need to retrieve a single array like this:

 [{ days: '2', people: 10 },
  { days: '2', people: 12 },
  { days: '4', people: 14 },
  { days: '5', people: 8 },
  { days: '5', people: 8 }]

Then I need to sum the total number of people for each "days" key with a common value. For example, I would want this new array:

[{ days: '2', people: 22 },
  { days: '4', people: 14 },
  { days: '5', people: 16 }]

To access my Firebase realtime database Im using web admin in Node.js



via Alex Devoid

No comments:

Post a Comment