1

Using Firebase and Angular 5, I am using the snapshot method to retrieve data without listening for changes. I want to keep each item's index/key as it is being used for a link to navigate to a page for the clicked item.

Here is the TS:

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

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

Logging (snapshot.val()) gives me an object (that I can't iterate over) of:

-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", …}

So, I used forEach to get all items one by one and push them to two different arrays if a condition is met.

      ..........
      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)
          }
      });
    })

  }

However, doing this means that I lose snapshot.key, which I need for navigation. How can I keep each item's snapshot.key for navigation / data purposes?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
cfoster5
  • 1,696
  • 5
  • 28
  • 42

1 Answers1

1

Firstly, it's not true that you can't iterate over the object returned by snapshot.val(). You can certainly iterate over the key/value pairs in a javascript object with for (x in y) syntax.

But if you want to iterate over the children in the snapshot while retaining the unique key, you could put that value into the child object:

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

Now you have an object for the snapshot with a new property called id that contains the unique key.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • How can I push `val.id` with the corresponding `val`? – cfoster5 Mar 06 '18 at 00:42
  • What do you mean? If you do what I suggest and add it as a property to val, it becomes part of the object that you push. I changed the code in my answer to reflect that. – Doug Stevenson Mar 06 '18 at 01:06
  • Ah, I see. I expected only `snapshot.val()` to be pushed as it is declared as `val` and `val` is being pushed. – cfoster5 Mar 06 '18 at 01:11