Reputation: 1826
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?
Upvotes: 1
Views: 1763
Reputation: 317372
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.
Upvotes: 1