Combining values in an Angular project to create a new object with the same properties using TypeScript

Hey there! I hope your day is going well. I'm currently working on calculating multiple objects to create a new one with average values.

Here's the schema:

export class stats{
  assists:number
  causedEarlySurrender:boolean
  champLevel:number
  ...
}

Then, I have this data in an array of objects like below:

0: {assists: 0, causedEarlySurrender: false, champLevel: 18, ...}
1: {assists: 2, causedEarlySurrender: false, champLevel: 18, ...}
2: {assists: 0, causedEarlySurrender: false, champLevel: 16, ...}

I've been experimenting but struggling to find a way to automate this process without having to manually type each key name.

This is what I have tried so far:

meanStats(){
    let iterator = 0;
    this.stats.forEach((m, i, array)=>{
      iterator ++;
      for (let [key, value] of Object.entries(m)) {
        console.log(key, value);
        switch (value) {
          case Boolean:
            if(key == "win"){
              this.wins += value//if true should compute as 1 and if its not should be 0
            }
            if(key == "gameEndedInSurrender"){
              this.surrenders += value
            }
            else{
              break
            }
            break;
          case Number:
          this.meanStat.key += value
            break;
          default:
            break;
        }
    }
      });
    
    }

The goal is to iterate through each key name and value, determine if it's a boolean or a number, sum that value on the correct key of the new object, and then divide all values by the iterator to obtain an average. The current issue is that 'key' is not recognized as a valid value of the object.

Any assistance on this matter would be greatly appreciated. Thank you in advance!

Answer №1

To address the issue of handling boolean values separately, you can implement a solution like this:

const obj = {};



let data = [
   {assists: 0, champLevel: 18, combatPlayerScore: 0, damageDealtToObjectives: 60241},
    {assists: 2, champLevel: 18, combatPlayerScore: 0, damageDealtToObjectives: 60241},
     {assists: 4, champLevel: 18, combatPlayerScore: 0, damageDealtToObjectives: 60241}
]

data.forEach( item => {
  Object.keys(item).forEach(key => {
    if (obj[key]) {
      obj[key]+= item[key];
    } else {
      obj[key]= item[key];
    }
  });
});
 Object.keys(obj).forEach((key) => obj[key] = obj[key]/data.length);

Answer №2

Sharing my findings here which may be helpful to some users. The process is not yet 100% complete as I still need to address booleans separately. Depending on the values, different approaches were taken such as averaging or using max values, making the task somewhat complex. Utilizing my object schema proved to be beneficial.

Below is the code snippet:

meanStats(){
    
    this.stats.forEach((m, i, array)=> {
      for (let [key, value] of Object.entries(m)) {

        // setting everything to default
        if(typeof(this.meanStat[key])=="undefined" && typeof(value)=="number"){
          this.meanStat[key] = 0
        }else if(typeof(this.meanStat[key])=="undefined" && typeof(value)=="boolean"){
          this.meanStat[key] = false

        }
        // filtering by number types              
        if (typeof(value) == "number"){
          let aux: number = this.meanStat[key]
          if (key == "largestCriticalStrike" || key == "largestKillingSpree"|| key == "largestMultiKill"){
            if(value > this.meanStat[key]){
              this.meanStat[key] = value
            }
          }else if (key == "doubleKills"|| key=="tripleKills"|| key == "quadraKills" || key== "pentakills"){
            switch (key) {
              // decided to make separate variables for these ones and also have average values.
              case "doubleKills":
                this.doublekills +=value
                aux+=value
                this.meanStat[key] = aux                
                break;
              case "tripleKills":
                this.triplekills +=value
                aux+=value
                this.meanStat[key] = aux  

                break;
              case  "quadraKills":
                this.quadrakills +=value
                aux+=value
                this.meanStat[key] = aux  
                break;
              case "pentakills":
                this.pentakills +=value
                aux+=value
                this.meanStat[key] = aux  
                break;
            
              default:
                break;
            }
          }else{
            aux+=value;
            this.meanStat[key] = aux;
          }
        }else{
          switch (key) {
            // need to handle other booleans, have not done that yet that's why there is only one case
            case "win":
                if(value == true){
                  this.wins ++
                }
              break;
          
            default:
              break;
          }
        }
    }
      });
        // average every number except largestCriticalStrike
    Object.keys(this.meanStat).forEach((key) => {
      if (typeof(this.meanStat[key])== "number"){
        if(key != "largestCriticalStrike" ){
          this.meanStat[key] = this.meanStat[key]/this.stats.length
        }        
      }      
    })
    console.log(this.meanStat)   
    console.log(this.wins)   
    } 
}

The code functions as intended, but if you have a better approach, please share your own answer. Have a great day! And thank you to @Arun Mohan for their assistance.

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

Retrieve data from a Firestore document in an Ionic application

I have a service that retrieves a specific document from Firestore using the getBidremains method. The method in the TypeScript class is called in ngOnInit like this: this.userInfo = this.firestoreService.getBidremains(userId).valueChanges().subscribe(da ...

how do I address the issue of Property 'navigation' not being found in type 'Readonly<{}> &'?

Here are two snippets of code that I am having trouble with: CustomHeader.tsx import { View, StyleSheet, Button } from 'react-native'; import { NavigationScreenProps } from 'react-navigation'; import Icon from 'react-native-vecto ...

Exploring the capabilities of UIGrid in conjunction with TypeScript DefinitelyTyped has been a

I've noticed that the latest release of UI Grid (RC3) has undergone significant architectural changes compared to nggrid. I am encountering some problems with the definitelytyped files for nggrid because they are from a different version. Will there ...

Converting JSON data into clickable URL links and retrieving information upon clicking

I have a dataset in JSON format. As I iterate through it, I'm inserting selected values into an HTML link element as shown below: getPatchList: function() { $.ajax({ url: "/returneddata" }).done(function(r ...

Dragging and dropping elements onto the screen is causing them to overlap when trying

I am having trouble merging the drag and drop functionality from Angular Material with resizing in a table. Currently, both features are conflicting and overlapping each other. What I am hoping for is to automatically cancel resizing once drag and drop s ...

What is the best way to integrate AWS-Amplify Auth into componentized functions?

Issue: I am encountering an error when attempting to utilize Auth from AWS-Amplify in separate functions within a componentized structure, specifically in a helper.ts file. Usage: employerID: Auth.user.attributes["custom:id"], Error Message: Pr ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

AngularJS throwing obscure error message when trying to access object

Whenever I try to access the object below, it results in an undefined error: { "code": 422, "message": { "address_info.email": [ "The address info.email field is required." ] }, "debug": null } In my code, when ...

Is it possible to maintain the input and output types while creating a function chain factory in

Take a look at the following code snippet involving pyramids: /** * @template T, U * @param {T} data * @param {(data: T) => Promise<U>} fn */ function makeNexter(data, fn) { return { data, next: async () => fn(data), }; } retu ...

Error Alert: "Invariant Violation" detected in a TypeScript program utilizing React

When attempting to implement the react-collapse component in my TypeScript application along with a custom d.ts file, I encountered the following error: Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a ...

Updating from webpack v1 to v2 using webpack-cli results in a tsx error during migration

Encountering an error during the build process after migration, I'm unsure if it's related to the recognition of tsx files or something within them that is causing issues: Failed to compile. Error in ./src/index_app.tsx Module parse fail ...

Discover the magic of transforming user input into live asterisks using Angular2 and TypeScript

Currently I have a unique input field that transforms text into asterisks as the user types: `<h5>Answer</h5><span><a href="#" (click)="plainText(answer.value)">(show) <input type="text" #answer (keyup)="asterisk(answer.value) ...

retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server? I am looking to save this data in a global store for future updates. I'm having trouble grasping the concept of asynchronous calls, such as in Redux. While I was able to understand it with simpl ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

Modify the Input Format of a Date from Y/M/D to D/M/Y in SQL/PHP using a form

Is there a way to switch the date format from Y/M/D to D/M/Y? The database stores dates as Y/M/D, but the input form requires D/M/Y format. Any suggestions on how to accomplish this format change? Please note that the Date is 'DOB' SQL Query: ...

What would cause the nsfw property to be absent from a TextChannel in client.on("messageCreate") event?

Currently working with Typescript in combination with Discord.js v14, I'm encountering the following error: Property 'nsfw' does not exist on type 'DMChannel | PartialDMChannel | ... Below is the snippet of problematic code: client.on( ...

Searching for a property in JSON using C# can be done by parsing the

Ensuring that every request in our ASP.Net Web API project is logged is a priority. Each request requires a search for a specific property/token (PersonId) within the payload, which must then be stored in the log table. The challenge arises from the fact ...

What is the best way to retrieve JSON data using perl?

Below is a snippet of JSON data I am working with: { "card":{ "cardName":"10AN10G", "portSignalRates":[ "10AN10G-1-OTU2", "10AN10G-1-OTU2E", "10AN10G-1-TENGIGE", "10AN10G-1-STM64" ], "listOfP ...

Regulation specifying a cap of 100.00 on decimal numbers entered into a text input field (Regex)

I have created a directive that restricts text input to only decimal numbers in the text field. Below is the code for the directive: import { HostListener, Directive, ElementRef } from '@angular/core'; @Directive({ exportAs: 'decimal ...

Issue with Typescript express application utilizing express-openid-connect wherein cookies are not being retained, resulting in an infinite loop of redirects

For a while now, I've been facing a block with no resolution in sight for this particular issue. Hopefully, someone out there can lend a hand. Background I have a TS express application running on Firebase functions. Additionally, I utilize a custom ...