Retrive alle values as array on key in firebase for react native

Hey i have a list of calendar evnets where the key is by date but i would like u get out all values as a array of data

but i wish to get the data out kinda like this but ofc with the rest of the values i have

'2012-05-25': [{date: '2021-04-10', name: "",},{date: '2021-04-10', name: "",}]

is there any way using firebase query to get it out in the format over ?

Database

Upvotes: 0

Views: 149

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

Something like this should do the trick:

cons ref = firebase.database.ref("calendar/events");
ref.once("value").then((snapshot) => {
  let result = {};
  snapshot.forEach((daySnapshot) => {
    result[daySnapshot.key] = [];
    daySnapshot.forEach((eventSnapshot) => {
      result[daySnapshot.key].push(eventSnapshot.val());
    })
  })
  console.log(result);
});

So we load all data from the database and then use two nested forEach loops to handle the dynamic levels underneath, and result[daySnapshot.key] to get the date key.

Upvotes: 1

Related Questions