Перебирать значения firebase - PullRequest
0 голосов
/ 30 мая 2020

Я хотел бы получить доступ к массиву комментариев и выполнить некоторые вычисления, чтобы отобразить среднее значение оценок (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); 
      }

Вот пример данных enter image description here

Ответы [ 2 ]

1 голос
/ 30 мая 2020
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);
}
1 голос
/ 30 мая 2020

Похоже, что «комментарии» - это объект, а не массив. поэтому вы не сможете получить число через "длину".

вы можете попробовать выполнить итерацию по ключам объекта.

см. Здесь: Как выполнить l oop через или перечислить объект JavaScript?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...