0

how to get id of object from firebase database in reactjs I have an array of list got from firebase database in react-redux , I want to get id of every object of array, How can I get?

2 Answers 2

2

Get the snapshot, and iterate through it as a Map, with Object.keys(foo).forEach for example. Here is a dummy piece of code :

`

      const rootRef = firebase.database().ref();
      const fooRef = rootRef.child("foo");
      fooRef.on("value", snap => {
        const foo = snap.val();
        if (foo !== null) {
          Object.keys(foo).forEach(key => {
            // The ID is the key
            console.log(key);
            // The Object is foo[key]
            console.log(foo[key]);
          });
        }
      });

`

Be careful with Arrays in Firebase : they are Maps translated into Arrays if the IDs are consecutive numbers started from '0'. If you remove an item in the middle of your array, it will not change the ID accordingly. Better work with Maps, it's more predictable.

Sign up to request clarification or add additional context in comments.

2 Comments

Can we get IDs from Array of objects coming from firebase ?
The same way, unless you use arrayName.forEach(/* Do your stuff here */) But once again, careful with Arrays in Firebase since they're stored as objects. More info here : firebase.googleblog.com/2014/04/…
0

You could try something like this:

export const getAllRooms = () => {
  return roomCollection.get().then(function (querySnapshot) {
    const rooms = [];
    querySnapshot.forEach(function (doc) {
      const room = doc.data();
      room.id = doc.id;
      rooms.push(room);
    });
    return rooms;
  });
};
`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.