Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
Add values of objects fields in array and calculate average

I have an object UserScore. It has field called score that is an number. I am keeping all userscores in userScores variable and overallScore for average of scores.

public userScores: any = [];
public overallScore : number = 0;

I tried so far something like this:

   sumRatingValues(): void{
    let i = 0;
    this.userScores.forEach((score: any) => {
      this.overallScore += score.score;
      i++;
      console.log(this.overallScore);
    });
    this.overallScore / i;
  }

Then I am using this method in ngOnInit.

But it doesn't print to conole log anything and overallScore value is 0.

EDIT How I fetch data:

getRating(){
    this.route.params
    .subscribe((params: Params) => {
      const id = params['id'];
      this.sharedService.getRecipesScoresForRecipe(id).subscribe(scores =>{
        this.userScores = scores;
        console.log(this.userScores)
      })
  });
  }

console.log prints out properly objects with their fields and value enter image description here And my ngOnInit:

ngOnInit(): void {
    ...
    this.getRating();
    this.sumRatingValues();
}

Little testing on front:

<div class="class" *ngFor="let user of userScores">{{user.score}} - {{overallScore}}</div>

This is how it look like: result

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda