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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How can I push val.id with the corresponding val?
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.
Ah, I see. I expected only snapshot.val() to be pushed as it is declared as val and val is being pushed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.