Getting JSON Key Value from Firebase Datasnapshot

半城伤御伤魂 提交于 2020-08-25 04:26:19

问题


Meanwhile I am developing a Flutter app with Firebase and it is enjoyable indeed, of course there is hassle to overcome...

I setup a Firebase datastore, and through the firebase_database plugin I got a DataSnapshot returned as follow:

FirebaseDatabase.instance.reference().child('users')
  .orderByChild('emailAddress')
  .equalTo('wonderjimmy@gmail.com').once()
  .then((onValue) {
   Map data = onValue.value;
  });

I use a Map object to keep this JSON. A stupid question: if I just want to get the value "-L474-TYYYGPvCChlZCS", how should I do?


回答1:


for accessing the key from DataSnapshot just use snapshot.key and you will have the relative key of the item in your case Users

 .then((onValue) {
   onValue.map(data => {
      var key = data.key
    })
 });

or just use as given in firebase docs inside then

.then(function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var key = childSnapshot.key; // you will get your key here
  });
});



回答2:


You can get the key by snapshot.key, you can find a reference to it here:

snapshot.forEach(function(childSnapshot) {
  var childKey = childSnapshot.key;
  var childData = childSnapshot.val();
  // ...
});

https://firebase.google.com/docs/database/web/lists-of-data#listen_for_value_events




回答3:


This worked for me:

.then(res => {
      // console.log(res)
      const data = res.data
      // extracting firebase ids for manipulating existing notes
      for (let key in data) {
        const item = data[key]
        item.id = key
        console.log(item.id)
      }


来源:https://stackoverflow.com/questions/48536748/getting-json-key-value-from-firebase-datasnapshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!