A guide to finding the mean in Angular by utilizing JSON information

import {
  Component,
  OnInit
} from "@angular/core";
import {
  MarkService
} from "../app/services/marks.service";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
  title = "my-test";
  public students = [];
  allStudents: any = [];
  average: any = [];

  constructor(private _marksService: MarkService) {}

  ngOnInit() {
    this._marksService.getMarks().subscribe(data => (this.students = data));
  }

  calHandle(i) {
    var data = this.students;
    this.average = Object.values(data).reduce(
      (avg, {
        values
      }, _, {
        length
      }) => avg + values / length,
      0
    );
  }
}
<table border="1">
  <tr>
    <th>Name</th>
    <th>Jan</th>
    <th>Feb</th>
    <th>March</th>
    <th>April</th>
    <th>action</th>
    <th>Average</th>
    <!-- </tr> -->
    <tbody *ngFor="let item of students; let i = index;">
      <tr>
        <td>{{item.name}}</td>
        <td>{{item.jan}}</td>
        <td>{{item.feb}}</td>
        <td>{{item.march}}</td>
        <td>{{item.April}}</td>
        <td><button (click)="calHandle(i)">calculate</button></td>
        <td>{{average}}</td>
      </tr>
    </tbody>

</table>

<!--
json data

[
 {"name": "josh", "jan":20,"feb":32, "march":"50", "April":45},
 {"name": "peter", "jan":20,"feb":32, "march":"50", "April":45},
 {"name": "gorge", "jan":20,"feb":32, "march":"50", "April":45}
]

-->

I have created a code snippet to calculate the average student scores upon clicking a button. However, when I click the "calculate" button, the result is displayed as "NaN". I am seeking advice on how to ensure only numerical values are used to prevent this error and also how to properly display the average score for each individual student on button click.

Answer №1

Here's a different approach to solve the problem:

.ts

updateAverage(i: number) {
    let sum = 0;
    const keys = Object.keys(this.students[i]);
    keys.forEach(key => {
      if (key !== "name") {
        sum += Number(this.students[i][key]);
      }
    });
    this.students[i].average = sum / (keys.length - 1);
}

.html

<table border="1">
  <tr>
    <th>Name</th>
    <th>Jan</th>
    <th>Feb</th>
    <th>March</th>
    <th>April</th>
    <th>action</th>
    <th>Average</th>
    </tr>
    <tbody *ngFor="let item of students; let i = index;">
      <tr>
        <td>{{item.name}}</td>
        <td>{{item.jan}}</td>
        <td>{{item.feb}}</td>
        <td>{{item.march}}</td>
        <td>{{item.April}}</td>
        <td><button (click)="updateAverage(i)">calculate</button></td>
        <td>{{item.average}}</td>
      </tr>
    </tbody>
</table>

Check out the demo here!

Answer №2

To exclude the key 'name' from your object, you can utilize the Object.entries method:

const result = [
 {"name": "josh", "jan":20,"feb":32, "march":"50", "April":45},
 {"name": "peter", "jan":20,"feb":32, "march":"50", "April":45},
 {"name": "gorge", "jan":20,"feb":32, "march":"50", "April":45}
].map(getAverage);

function getAverage(obj) {
  return Object.entries(obj).reduce((avg, obj, _, { length }) => obj[0] == 'name' ? avg : avg + obj[1] / length, 0);
}


console.log(result);

Applying this concept to your specific scenario looks like this:

calHandle(i) {
  var data = this.students;
  this.average = Object.entries(data).reduce(
    (avg, obj, _, {
      length
    }) => obj[0] == 'name' ? avg : avg + obj[1] / length,
    0
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble receiving values sent through AJAX POST requests to PHP

Can anyone help me figure out why my AJAX POST method is not sending the specific section of my URL string to my PHP file? I've checked everything and can't seem to find where the issue lies. When I var_dump the POST variable in my PHP file, it s ...

Having trouble with querySelector or getElementById not functioning properly?

Currently, I am in the midst of developing an experimental web application that features a quiz component. For this project, I have implemented a Python file to handle the questions and quiz functionalities. However, I have encountered an issue with the Ja ...

What steps can I take to identify and manage a browser's inability to play a media file?

I am currently utilizing a JavaScript utility to stream mp3 content. Unfortunately, there are instances where I direct users to a file that cannot be played due to external factors. In such cases, Firebug displays an error message indicating that the file ...

Angular2 application experiences exception in the karma test for checking karma

Is there a way for me to access more detailed logs? I'm struggling to pinpoint where the error is originating from. A critical error occurred while running my code: Chrome 57.0.2987 (Linux 0.0.0) ERROR Uncaught Response with status: 0 for URL: null ...

Utilize Angular's effect() function to reset a form when a specific signal becomes true

Is my approach to using signals correct in this scenario? I have a form that needs to reset when the success signal is true. I implemented this with an effect, but the Angular documentation is not very clear on this topic yet (refer to here). **Do you bel ...

Making various API calls using Python's JSON module

Struggling to handle multiple requests to an API, consolidate responses, and convert the data into a dataframe. The issue lies in creating the dataframe with JSON files as it results in an empty dataframe despite gathering necessary data. Removing 'df ...

Middleware for Redux in Typescript

Converting a JavaScript-written React app to Typescript has been quite the challenge for me. The error messages are complex and difficult to decipher, especially when trying to create a simple middleware. I've spent about 5 hours trying to solve an er ...

Tips on how to include a single quote within a JSON value when making a webservice call

I am attempting to connect to a JSON ASP.NET web service using .NET. Everything goes smoothly when I send " { county : 'whatever' } ", but I encounter a 500 Internal Server Error when I try something like " { county : 'It\'s ok&ap ...

Turn off bodyparser when uploading files in Node.js

This query is quite similar to another one on Stack Overflow regarding how to disable Express BodyParser for file uploads in Node.js. The solution provided there was for Express3, but when tested with the updated Express 4, it didn't work as expected. ...

Guide to utilizing CURL and SAML TOKEN authentication for invoking REST APIs

Here is an example of my URL: https://<ip:port>/TestRESTServices/objects/test-folder Below is the JSON data I would like to send: { "name":"test-1", "parent-uuid":"126" } I am trying to create a folder named test-1 by making a POST request ...

Include an additional component in the array that is already in place

The provided data currently consists of an array with three elements. (3) [{…}, {…}, {…}] 0: {Capacity: "150", Series: "20", Make: "150", Model: "150", TowerHeight: "151", …} 1: {Capacity: ...

Operating PHP program from html on Beaglebone Black Rev C Debian

I've created a JavaScript program that utilizes node.js to manage GPIO from an IO.html page to the beaglebone. I simply initiate the JavaScript with "node myscript.js". Now, I'm looking to incorporate a PHP file that will store data from the IO. ...

Loop through JSON results in Ionic using Angular

I am struggling to retrieve data from a JSON file in Object format using Typescript. When I try to fetch the data from the API, it doesn't display as expected. Typescript this.http.get('http://example.com/api') .subscribe((data) => { ...

What is the best way to locate an item within a JSON document and modify the value associated with a specific key?

My JSON file has the following structure: [ { "domain": "abc.com", "action": "no action", "date": "2020-05-15", "status": "new" }, { "domain": "xyz.net", "action": "pending", "date": "202 ...

Setting an if isset statement below can be achieved by checking if the variable

I have included a javascript function below that is designed to display specific messages once a file finishes uploading: function stopImageUpload(success){ var imagename = <?php echo json_encode($imagename); ?>; var result = '& ...

What is the method for accessing a validator that has been declared in a reactive form group while within the scope of a custom

Currently, I have a custom component that I am happy with and it is being used in a reactive form as shown below. private init() { const control4 = new FormControl("yy", Validators.pattern(".{2}")); const control5 = new FormControl("zz", Validators.pa ...

Unable to get jQuery click and hide functions to function properly

Hello, I am currently working on a program where clicking a specific div should hide its own class and display another one. However, the code does not seem to be functioning correctly. Below is my current implementation: $("#one").click(function(){ v ...

Can you help me streamline the code for the Sign Up Form app using React and jQuery?

Hi everyone, this marks my debut post on StackOverflow as I embark on the journey to become a full stack developer. To enhance my skills, I've been using FrontEnd Mentor for practice and managed to solve a challenge with the code provided below. Any s ...

Creating a network of communication between API routes in NextJS

Can the fetch API be used within an API route in NextJs? I have a large handler and instead of having everything in one handler, I'd like to modularize it so that after completing a specific task (e.g., writing to a database), I can call another handl ...

The element you are trying to interact with is currently not visible, therefore it cannot be accessed

Currently, I am working on a small Test Automation project using C# with Selenium WebDriver. I have run into an issue where some WebElements are not visible or have their 'Displayed' property set to 'false'. This prevents me from perfor ...