Divyanshu Bhaskar
Divyanshu Bhaskar

Reputation: 345

How to filter data from firebase?

BasicData {
userid:123123,
 email:[email protected]
 },
BusData {
Dropping: ....,
Boarding:......,
.....
 ......
 },
Traveller1 {
 name:....,
 seatno0.....,
 age:....,
 },
 Traveller2 {
 name:....,
 seatno0.....,
 age:....,

  },
 Traveller3 {
 name:....,
 seatno0.....,
age:....,
},
Traveller4 {
name:....,
seatno0.....,
age:....,

 }

In BookedBusdata there is table contains BasicData BusData and TravellerData. I want to access the the Data only consist of Travellers, But it may Traveller may be 2, 4 , 10 any number The Documents consist of only Map. But i want to all the data of Traveller which are in the form of Traveller1, Traveller2 whatever Traveller are there

   var docRef = db.collection("BookedTicketData").doc(orderid);
  docRef.get().then(function(doc) {
  if (doc.exists) {
     data = doc.data()
        console.log(data.Traveller1.Age) // I am getting the data if i am  accessing only one
  } else {
  // console.log("No such document!");
 }
  }).catch(function(error) {
     console.log("Error getting document:", error);
  });

This code i have performed

Upvotes: 0

Views: 37

Answers (1)

Dane Brouwer
Dane Brouwer

Reputation: 2962

If you're happy to filter the data client side, it's a fairly straight forward task

const data = {
  BasicData: {},
  BusData: {},
  Traveller1: {
    name: 'Name1',
    email: 'Email1'
  },
  Traveller2: {
    name: 'Name2',
    email: 'Email2'
  },
  Traveller3: {
    name: 'Name2',
    email: 'Email2'
  },
}

// returns an array of travelers
console.log(Object.keys(data).reduce((acc, key) => {
  if (key.includes('Traveller')) {
    acc.push(data[key])
  }
  return acc;
}, []))

// returns an object of travelers
console.log(Object.keys(data).reduce((acc, key) => {
  if (key.includes('Traveller')) {
    acc[key] = data[key];
  }
  return acc;
}, {}))

In your case you can just use Object.keys(doc.data()).reduce...

Upvotes: 2

Related Questions