我想访问comments数组并进行一些计算以得出评分(avgstars)的平均值,并显示我的Firebase数组中特定项目的评论数。
任何想法?
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);
}
看起来“ comments”是一个对象,not是一个数组。因此,您将无法通过“长度”获得数字。
您可以尝试通过对象键进行迭代。
参见此处:How do I loop through or enumerate a JavaScript object?
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);
}