【问题标题】:Retrieving name of object in firebase在firebase中检索对象的名称
【发布时间】:2016-08-04 18:45:25
【问题描述】:

我有一个按数字组织的对象列表/数组,我将对象名称视为“id”。我正在使用 firebase,但我不知道如何获取 ID 号本身。任何帮助都会很棒

//js
  myFirebaseRef.once("value", function(snapshot) {
   var list = snapshot.val();
    $scope.items = list
     console.log($scope.items)
  })
//log $scope.items
[1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object //...

【问题讨论】:

    标签: javascript angularjs node.js firebase firebase-realtime-database


    【解决方案1】:

    像angular.forEach 这样你可以在附近做点什么:

    angular.forEach($scope.items,function(key,value){
       //the key will contain your id
       console.log(key);
    })
    

    【讨论】:

    • 谢谢,但记录了对象及其项目,而不是对象的 ID/名称Object {des: "Coffee Shop", name: "Joes Cafe", rate: "2"}
    • 我必须在我的模板中获取该 ID。它应该是什么样子? {{钥匙}} ?不工作
    • 你的意思是对象检索有一个属性名称?如果是这种情况,您可以在函数中使用 value.name
    • 为了在模板中显示它,您可以使用 ng-repeat。像
      {{key}}
    【解决方案2】:

    这是你要找的吗?

    myFirebaseRef.once("value", function(snapshot) {
      //var list = snapshot.val();
      snapshot.forEach(function(itemSnapshot) {
        console.log(itemSnapshot.key); // if you're using 2.x that is key()
      });
    })
    

    【讨论】:

      【解决方案3】:

      像这样。您使用obj[key] = value; 来设置带有变量的id。

      function update(node,key,value){
          var ref = firebase.database().ref('/');
          var obj = {};
          obj[key] = value;
          ref.child(node).update(obj)
          .then(function() {
              console.log('Update Ran Successfully');
          });       
      }
      

      【讨论】:

        【解决方案4】:

        这是一个真实的例子,使用 react 和 axios 在 firebase 中检索对象的名称:

        componentDidMount() {
            axios.get('/uri.json')
                .then(res => {
                    let fetchedData = [];
                    for (let key in res.data) {
                        fetchedData.push({
                            ...res.data[key],
                            id: key //The key here holds the object's name !
                        });
                    }
                });
        }
        

        【讨论】:

          猜你喜欢
          • 2020-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-21
          • 1970-01-01
          相关资源
          最近更新 更多