如何从reactjs中的firebase数据库获取对象的id

时间:2022-12-07 22:03:15

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?

如何从reactjs中的firebase数据库获取对象的id我有一个从react-database中的firebase数据库获取的列表数组,我想得到数组的每个对象的id,我怎么能得到?

1 个解决方案

#1


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 :

获取快照,并使用Object.keys(foo).forEach作为Map迭代它。这是一段虚拟代码:

`

      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.

注意Firebase中的数组:如果ID是从'0'开始的连续数字,它们会被映射为数组。如果删除阵列中间的项目,则不会相应地更改ID。更好地使用地图,它更容易预测。

#1


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 :

获取快照,并使用Object.keys(foo).forEach作为Map迭代它。这是一段虚拟代码:

`

      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.

注意Firebase中的数组:如果ID是从'0'开始的连续数字,它们会被映射为数组。如果删除阵列中间的项目,则不会相应地更改ID。更好地使用地图,它更容易预测。