Firebase快照返回对象而不是数组以进行迭代

问题描述 投票:1回答:1

使用Firebase和Angular 5,我使用快照方法检索数据而不监听更改。我希望保留每个项目的索引/键,因为它用于链接以导航到所单击项目的页面。

这是TS:

  features = [];
  notfeatures = [];
  constructor(private Svc: Service, private http: HttpClient){

    firebase.database().ref('/reviews').once('value').then((snapshot)=> {
      console.log("snapshot", (snapshot.val()));
    ..........

记录(snapshot.val())给了我一个对象(我不能迭代):

-L6ZwjBbyi4jz21OEoST: {category: "Movies", contributor: "CF1", feature: "No", …}

randomkey1: {category: "Movies", contributor: "CF1", feature: "No", …}

randomkey2: {category: "Movies", contributor: "DS1", feature: "Yes", …}

randomkey3: {category: "TV", contributor: "KH1", feature: "No", …}

因此,我使用forEach逐个获取所有项目,并在满足条件时将它们推送到两个不同的数组。

      ..........
      snapshot.forEach(snapshot => {
          console.log(snapshot.key, snapshot.val());
          if (snapshot.val().feature == "Yes") {
            this.features.push(snapshot.val())
            console.log("feature", this.features)
          }
          if (snapshot.val().feature == "No") {
            this.notfeatures.push(snapshot.val())
            console.log("notfeature", this.notfeatures)
          }
      });
    })

  }

但是,这样做意味着我失去了导航所需的snapshot.key。如何保存每个项目的snapshot.key用于导航/数据目的?

javascript angular firebase firebase-realtime-database
1个回答
1
投票

首先,你不能迭代snapshot.val()返回的对象是不正确的。你当然可以用iterate over the key/value pairs in a javascript object语法for (x in y)

但是,如果要在保留唯一键的同时迭代快照中的子项,可以将该值放入子对象中:

const val = snapshot.val()
val.id = snapshot.key
this.features.push(val)

现在,您有一个快照对象,其中包含一个名为id的新属性,该属性包含唯一键。

© www.soinside.com 2019 - 2024. All rights reserved.