Reputation: 25
I would like to access the comments array and do some calculations to render the average of ratings (avgstars) and show the numbers of comments on a particular item in my firebase array.
Any idea?
ngOnInit() {
this.route.params
.pipe(switchMap((params: Params) => this.dishservice.getDish(params['id'])))
.subscribe(dish => {
this.dish = dish
this.favorite = this.favoriteService.isFavorite(this.dish.id);
//compute the average of the comments and the render the length of the array
this.numcomments = /* This is the locus --->*/ this.dish.comments.length;
let total =0;
this.dish.comments.forEach(comment =>total += comment.rating);
this.avgstars = (total/this.numcomments).toFixed(2);
},
errmess => this.errMess = <any>errmess);
}
Upvotes: 0
Views: 32
Reputation: 565
You don't have change your firebase data model as long as you create a new Array by iterating your "key" (-M8V...) values from the "comments" object.
I would do something like this:
let p = this.dish[0].comments;
for (let [key, value] of Object.entries(p)) {
console.log(key, value);
}
Upvotes: 1
Reputation: 565
It looks like "comments" is an object and not an array. therefore you will fail getting a number via "length".
you may try it iterate thru the object keys.
see here: How do I loop through or enumerate a JavaScript object?
Upvotes: 1