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
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.
2 Comments
Naveed Aheer
Can we get IDs from Array of objects coming from firebase ?
Victor Baron
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/…