1

I am trying to create a class for each nfl team. in my code below you can see I create two https requests to an external API. the first request creates a class for each NFL team and has various standing data, the second request then creates two different class objects for each team. One for offensive stats and one for defensive stats.

My desired result is to have the offensive stats class and defensive stats class be appended onto the Nfl_team class based off of it matching the Team property. So instead of returning three different classes for each team it should be one class for each nfl team, with two sub-classes for the offensive and defensive stats. Can somebody help me or point me in the right direction?! I'm totally lost on how to even do this and can't find anything online, maybe I just don't know what to look for. Any help would be great.

You can find the api key in the comments

get_teams.js

import axios from 'axios';
import Nfl_team from '../models/teamModel.js';
import Offensive_stats from '../models/offensiveStatsModel.js'
import Defensive_stats from '../models/defensiveStatsModel.js';
import colors from 'colors';
import dotenv from 'dotenv';
dotenv.config();


let team = {};

axios.all([
        axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/2019?key=${process.env.API_KEY}`),
        axios.get(`https://api.sportsdata.io/api/nfl/odds/json/TeamSeasonStats/2019?key=${process.env.API_KEY}`)
    ])
    .then(function (responseArr) {

        /* Create a for each loop that goes over each obj and returns a new team object using NFL 
         team model with updated stats from sportsdata.io 
       __________________________________________________________________________________________*/

        responseArr[0].data.forEach(element => {

            let team = {
                [element.Team]: new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
                    element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
                    element.PointsFor, element.PointsAgainst)
            }

            // console.log(`Model for ${element.Name}: `.bold.brightBlue)
            // console.log(team);

            

        })

        responseArr[1].data.forEach(element => {

            let offensive_stats = new Offensive_stats(element.Team, element.Touchdowns, element.RushingYardsPerAttempt,
                element.PassingYardsPerAttempt, element.CompletionPercentage, element.PasserRating, element.TimesSacked,
                element.QuarterbackHits, element.OffensivePlays);

            // console.log(`Offensive Stats Model for ${element.Team}: `.bold.brightBlue)
            // console.log(offensive_stats);
            // console.log(`qb hit percentage = ${offensive_stats.quarterback_hits_percentage}`.bold.brightRed);

            console.log(team);
        })

        responseArr[1].data.forEach(element => {

            let defensive_stats = new Defensive_stats(element.Team, element.OpponentTouchdowns, element.OpponentRushingYardsPerAttempt,
                element.OpponentPassingYardsPerAttempt, element.OpponentCompletionPercentage, element.OpponentPasserRating, element.OpponentTimesSacked,
                element.OpponentQuarterbackHits, element.OpponentOffensivePlays);

            // console.log(`Defensive Stats Model for ${element.Team}: `.bold.brightBlue)
            // console.log(defensive_stats);
            // console.log(`opponent qb hit percentage = ${defensive_stats.opponent_quarterback_hits_percentage}`.bold.brightRed);
        })

    })
    .catch(function (error) {
        // handle error
        console.log(error);
    })

team_model.js

export default class Nfl_team {
    constructor(team=String, name=String, wins=Number, losses=Number, ties=Number, win_percentage=Number,
         division_wins=Number, division_losses=Number, division_ties=Number, points_for=Number, points_against=Number, offensive_stats, defensive_stats) {
        this.team = team;
        this.name = name;
        this.wins = wins;
        this.losses = losses;
        this.ties = ties;
        this.win_percentage = win_percentage;
        this.division_wins = division_wins;
        this.division_losses = division_losses;
        this.division_ties = division_ties;
        this.points_for = points_for;
        this.points_against = points_against;
        this.offensive_stats = {};
        this.defensive_stats = {};
    }

    get record() {
        return [this.wins,this.losses,this.ties];
    }

    get division_record() {
        return [this.division_wins, this.division_losses, this.division_ties];
    }
}

offensive_stat_model.js

export default class Offensive_stats {

    constructor (team, touchdowns, rushing_yards_per_attempt, passing_yards_per_attempt, completion_percentage, passer_rating, 
   times_sacked, quarterback_hits, offensive_plays) {
        this.team = team;
        this.touchdowns = touchdowns;
        this.rushing_yards_per_attempt = rushing_yards_per_attempt;
        this.passing_yards_per_attempt = passing_yards_per_attempt;
        this.completion_percentage = completion_percentage;
        this.passer_rating = passer_rating;
        this.times_sacked = times_sacked;
        this.quarterback_hits = quarterback_hits;
        this.offensive_plays = offensive_plays;
    }

    get quarterback_hits_percentage() {
        return this.offensive_plays / this.quarterback_hits;
    }
}

defensive_stat_model.js

export default class Defensive_stats {

    constructor (team, opponent_touchdowns, opponent_rushing_yards_per_attempt, oppenent_passing_yards_per_attempt, opponent_completion_percentage,
    opponent_passer_rating, opponent_times_sacked, opponent_quarterback_hits, opponent_offensive_plays) {
        this.team = team;
        this.opponent_touchdowns = opponent_touchdowns;
        this.opponent_rushing_yards_per_attempt = opponent_rushing_yards_per_attempt;
        this.oppenent_passing_yards_per_attempt = oppenent_passing_yards_per_attempt;
        this.opponent_completion_percentage = opponent_completion_percentage;
        this.opponent_passer_rating = opponent_passer_rating;
        this.opponent_times_sacked = opponent_times_sacked;
        this.opponent_quarterback_hits = opponent_quarterback_hits;
        this.opponent_offensive_plays = this.opponent_offensive_plays;
    }

    get opponent_quarterback_hits_percentage() {
        return this.opponent_offensive_plays / this.opponent_quarterback_hits;
    }
}

2 Answers 2

1

One solution:

Modify the team model to include placeholders for offStats and defStats - or something, then:

  1. Collect the teams into an object literal teams like this:

{ [element.Team] : team } // {Ravens : Nfl_team_object}

  1. While looping over the stats, in each loop do:

teams[element.Team].offStats = new Offensive_stats(...)

teams[element.Team].defStats = new Defensive_stats(...)

Or, using your existing code:

teams[element.Team].offStats = offensive_stats;

Each team will be composed of the team meta-data plus both related off/def stats objects.

Here is the code:

axios.all([
    axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/2019?key=${process.env.API_KEY}`),
    axios.get(`https://api.sportsdata.io/api/nfl/odds/json/TeamSeasonStats/2019?key=${process.env.API_KEY}`)
  ])
  .then(function(responseArr) {
    responseArr[0].data.forEach(element => {
      teams[element.Team] = new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
        element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
        element.PointsFor, element.PointsAgainst)
    });

    responseArr[1].data.forEach(element => {
      teams[element.Team]['offensive_stats'] = new Offensive_stats(element.Team, element.Touchdowns, element.RushingYardsPerAttempt,
        element.PassingYardsPerAttempt, element.CompletionPercentage, element.PasserRating, element.TimesSacked,
        element.QuarterbackHits, element.OffensivePlays);
    });

    responseArr[1].data.forEach(element => {
      teams[element.Team]['defensive_stats'] = new Defensive_stats(element.Team, element.OpponentTouchdowns, element.OpponentRushingYardsPerAttempt,
        element.OpponentPassingYardsPerAttempt, element.OpponentCompletionPercentage, element.OpponentPasserRating, element.OpponentTimesSacked,
        element.OpponentQuarterbackHits, element.OpponentOffensivePlays);
    });
    console.log(teams);

  })
  .catch(function(error) {
    // handle error
    console.log(error);
  })
Sign up to request clarification or add additional context in comments.

10 Comments

the team object is outside of the scope of the second loop though. I am making two seperate calls to the api.
right, create the teams variable outside the first axios call. then, it is available inside the entire structure of nested .then() calls.
To be clear, create teams like this: const teams = {};
Put this up on stackblitz or repl.io or someplace with some mock data. I can't guess at what you're doing, but I can certainly make it work given the starter code you have above.
Please see the updated answer and REPL repl.it/@JordanVera1/nflModel#index.js
|
0

was a scope issue.

import axios from 'axios';
import Nfl_team from '../models/teamModel.js';
import Offensive_stats from '../models/offensiveStatsModel.js'
import Defensive_stats from '../models/defensiveStatsModel.js';
import colors from 'colors';
import dotenv from 'dotenv';
dotenv.config();


let team = {};

axios.all([
        axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/2019?key=${process.env.API_KEY}`),
        axios.get(`https://api.sportsdata.io/api/nfl/odds/json/TeamSeasonStats/2019?key=${process.env.API_KEY}`)
    ])
    .then(function (responseArr) {

        /* Create a for each loop that goes over each obj and returns a new team object using NFL 
         team model with updated stats from sportsdata.io 
       __________________________________________________________________________________________*/

        responseArr[0].data.forEach(element => {

            team = {
                [element.Team]: new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
                    element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
                    element.PointsFor, element.PointsAgainst)
            }

            // console.log(`Model for ${element.Name}: `.bold.brightBlue)
            // console.log(team);

            

        })

        responseArr[1].data.forEach(element => {

            let offensive_stats = new Offensive_stats(element.Team, element.Touchdowns, element.RushingYardsPerAttempt,
                element.PassingYardsPerAttempt, element.CompletionPercentage, element.PasserRating, element.TimesSacked,
                element.QuarterbackHits, element.OffensivePlays);

            // console.log(`Offensive Stats Model for ${element.Team}: `.bold.brightBlue)
            // console.log(offensive_stats);
            // console.log(`qb hit percentage = ${offensive_stats.quarterback_hits_percentage}`.bold.brightRed);

            team.offensive_stats = offensive_stats;

            console.log(team);
        })

        responseArr[1].data.forEach(element => {

            let defensive_stats = new Defensive_stats(element.Team, element.OpponentTouchdowns, element.OpponentRushingYardsPerAttempt,
                element.OpponentPassingYardsPerAttempt, element.OpponentCompletionPercentage, element.OpponentPasserRating, element.OpponentTimesSacked,
                element.OpponentQuarterbackHits, element.OpponentOffensivePlays);

            // console.log(`Defensive Stats Model for ${element.Team}: `.bold.brightBlue)
            // console.log(defensive_stats);
            // console.log(`opponent qb hit percentage = ${defensive_stats.opponent_quarterback_hits_percentage}`.bold.brightRed);
        })

    })
    .catch(function (error) {
        // handle error
        console.log(error);
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.