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

Unable to smoothly expand Div in React using Tailwind

I'm facing a challenge in animating a div that contains input elements. I want it to expand smoothly - initially, the text area is small and the other two inputs and buttons are hidden. When clicking on the text area, the input and button should be re ...

Retrieve the innerHTML contents from all span elements

I'm having trouble getting the content of all span tags that are child elements of div#parent. So far, I've only been able to retrieve the content of the first one. Can someone please assist me with this? $( document ).ready(function() { ...

When attempting to upgrade from Angular 10 to 13, users may encounter the following error message: "TS2307: Unable to locate module 'path_to_service' or its corresponding type declarations."

I initially developed my Angular App using the paper-dashboard template with Angular version 10.0. Recently, I upgraded to Angular version 13 and switched to a different template - WrapPixel. However, I encountered an error when trying to include a servi ...

Unable to import CSV file

I'm currently in the process of developing a CSV editor that involves importing a CSV file and converting it into HTML tables. Below is the code I have been working on: <html> <head> <title></title> </head> <body& ...

Analyzing - Dynamically Tagging Method - Implementing direct call regulations- Erase enduring variables

https://i.sstatic.net/elGJz.jpg Hello there, I am currently utilizing a Direct call rule within DTM. When I click on a href link that opens in a new window, I want to remove or clear the eVars and events associated with the click. I have implemented custo ...

Steps to resolve the days.map error:

My map function is, days.map((val)=>val) Upon consoling the days prop, I receive the following output: [Array(7)] 0: (7) ['', '', '', 'Wednesday', '', '', 'Saturday'] length: ...

"What sets apart the usage of `import * as Button` from `import {Button}`

As a newcomer to Typescript, I am facing an issue while trying to import a react-bootstrap Button. In scenario 1: import {Button} from 'react-bootstrap/lib/Button' In scenario 2: import * as Button from 'react-bootstrap/lib/Button' B ...

Issue with npm resolution due to package requiring another third-party dependency

I'm encountering an issue with a requirement and I'm hoping for some assistance. I currently have a package called @unicoderns/orm that relies on mysql, which can be found at https://github.com/unicoderns/ORM Now I'm working on developing ...

What is the best method for transferring a string from JavaScript to a JSON file?

Is there a way to update the value of "JSValue" in my JSON (JSValue) using JavaScript? Specifically, how can I assign JSValue to a variable called Value using JavaScript? JavaScript var Value = 1 + 1 JSON { "DATA": [ { "JSValue": "0" } ...

The Trouble with Vue.js 2 and Axios Scopes

I previously encountered this "problem" but can't recall the correct approach to achieve the desired results. My current setup involves using Vue 2 to load data into variables that are then displayed on the HTML side: window.Vue = require('vue&a ...

Unable to retrieve the filtered results using JSON_VALUE

Trying to utilize the feature of MS SQL 2016 - JSON_VALUE has been a challenge for me... I have a set of objects in JSON form saved in a field within the database for each entry. For example: [{"CommunicatorType":0,"UserName":"SkypeUser"},{"Communicator ...

Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

Deactivate the Mention and Hash tag in ngx-linkifyjs

I am currently utilizing ngx-linkifyjs to automatically convert URLs in text to clickable hyperlinks. However, I am facing an issue where it is also converting # and @ tags into links. Is there a way to prevent the conversion of # and @ while maintain ...

Attempting to display a grid of product listings using a Websocket connection and an Express server

Recently, I attempted to create a live table of products using websockets for real-time updates. While I am new to this concept, I decided to upgrade an old project with websockets. Unfortunately, my attempts were unsuccessful, which is why I am seeking he ...

Update the second mouse click functionality using jQuery

I currently have a jQuery function integrated into my WordPress portal that manages the functionality of the menu and the display of subcategories to ensure proper mobile optimization. This code, which was created by the theme editor, handles these aspects ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...

JavaScript: Incorporating an operator into a specific object (instead of the entire class)

Are you familiar with how to include an operator in an object (rather than the entire class)? When it comes to a method, I know you can achieve that by: my_object.new_function = function(){return 1}; Then invoking my_object.new_function() will output ...

Injecting CSS styles into dynamically inserted DOM elements

Utilizing Javascript, I am injecting several DOM elements into the page. Currently, I can successfully inject a single DOM element and apply CSS styling to it: var $e = $('<div id="header"></div>'); $('body').append($e); $ ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

Vue's bidirectional data binding presents a challenge when attempting to update the parent component from a child component

I have the following components: Parent Component: <template> <v-container> <v-row class="text-center"> <v-col cols="12" class="parent"> <p>I am the Parent component</p> ...