Determining season goals for teams using nested JSON data

Is it possible to retrieve a team's total goals scored for the season from the provided data by using the team's name as the input for a function?

Would it be accurate to attempt mapping over the rounds and filtering matches where either team1 or team2 is equal to the inputted team, then reducing the sum of those scores?

Here is a condensed sample of the data:

{
  "name": "English Premier League 2014/15",
  "rounds": [
    {
      "name": "Matchday 1",
      "matches": [
        {
          "date": "2014-08-16",
          "team1": {
            "key": "manutd",
            "name": "Manchester United",
            "code": "MUN"
          },
          "team2": {
            "key": "swansea",
            "name": "Swansea",
            "code": "SWA"
          },
          "score1": 1,
          "score2": 2
        },
        {
          "date": "2014-08-16",
          "team1": {
            "key": "leicester",
            "name": "Leicester City",
            "code": "LEI"
          },
          "team2": {
            "key": "everton",
            "name": "Everton",
            "code": "EVE"
          },
          "score1": 2,
          "score2": 2
        }, 

This is my current approach:

function calculateGoals (teamName){

    function sumScores (total, match) {
        return total + match.score1;
    }


    fetch('https://raw.githubusercontent.com/openfootball/football.json/master/2014-15/en.1.json')
    .then(response => response.json())
    .then(data => console.log(data.rounds.map( round => round.matches.filter(match => match.team1.name === teamName).reduce(sumScores))));

}

calculateGoals('Liverpool')

Answer №1

Give this a try

function calculateScoreByTeamName(strTeam){

  let leagueData = {
    "name": "English Premier League 2014/15",
    "rounds": [
      {
        "name": "Matchday 1",
        "matches": [
          {
            "date": "2014-08-16",
            "team1": {
              "key": "manutd",
              "name": "Manchester United",
              "code": "MUN"
            },
            "team2": {
              "key": "swansea",
              "name": "Swansea",
              "code": "SWA"
            },
            "score1": 1,
            "score2": 2
          },
          {
            "date": "2014-08-16",
            "team1": {
              "key": "leicester",
              "name": "Leicester City",
              "code": "LEI"
            },
            "team2": {
              "key": "everton",
              "name": "Everton",
              "code": "EVE"
            },
            "score1": 2,
            "score2": 2
          }
        ]
      }
    ]
  };

  let totalScore = 0;

  for(week of leagueData.rounds){
      for(game of week.matches){
          if(game.team1.name == strTeam){
              totalScore += game.score1;
          }else if(game.team2.name == strTeam){
              totalScore += game.score2;
          }
      }
  }

  console.log(totalScore);

}

//Test the function with this call
calculateScoreByTeamName("Swansea");

You can check the code by pasting it in an online JavaScript editor

Hope this information is useful!

Answer №2

In my implementation using a functional programming approach, I have included comments above each function expression declaration:

const JSON_URL = 'https://raw.githubusercontent.com/openfootball/football.json/master/2014-15/en.1.json'

const downloadData = () =>
  fetch(JSON_URL).then(response => response.json())

const calculateSum = (total, value) => total + value

// Calculate the score for a specific team in a match
const resultPerMatch = teamName => match => {
  if (match.team1.name === teamName) return match.score1
  if (match.team2.name === teamName) return match.score2
  
  // If the chosen team did not play this game, it gets 0 points
  return 0
}

// Sum up the scores of a team for each match in a round
const resultsPerRound = teamName => round =>
  round.matches.map(resultPerMatch(teamName)).reduce(calculateSum, 0)

// Sum up the total scores of a team for all rounds
const resultsPerTeam = (data, teamName) => {
  return data.rounds.map(resultsPerRound(teamName)).reduce(calculateSum, 0)
}

// Wait for the data to be downloaded before calculating results
downloadData().then(data => {
  console.log(resultsPerTeam(data, 'Manchester United'))  // 62
  console.log(resultsPerTeam(data, 'Liverpool'))          // 52
})

Answer №3

Appreciate the assistance with combining different approaches to fetch and process data using for loops in my solution. Your help has been invaluable!

async function calculateTeamScore(teamName) {
    const response = await fetch('https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json');
    const jsonData = await response.json();

    let totalScore = 0;

    for(const round of jsonData.rounds){
        for(const match of round.matches){
            if(match.team1.name === teamName){ 
                totalScore += match.score1;
            } else if(match.team2.name === teamName) {
                totalScore += match.score2;
            }
        }
    }

    console.log('The total goals scored by ' + teamName + ' this season is: ' + totalScore);
}

calculateTeamScore('Liverpool');

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

Rails 4 does not properly handle the execution of Ajax responses

Currently, I am incorporating ajax functionality within my Rails application. Within the JavaScript file of my application, the following code snippet is present: $('#request_name').on('focusout', function () { var clientName ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...

Unable to get the Express.js Router functioning correctly on my server, even in a basic scenario

I am encountering an issue with using express.Router(). It was not functioning correctly in my application for serving JSON from MongoDB, so I attempted to simplify the scenario. However, I am receiving a 404 Not Found error in the request. What steps shou ...

Flashing tilemap during the update process

I'm attempting to create a game map on a canvas using a JSON file produced by tiled map editor. I believe I am close to accomplishing this, but I encounter one issue. When I include the call to load the map in my update function, the map flickers on ...

Transferring an array of Json objects to Firestore

My Json object Array is meticulously organized and quite extensive, following this format: { "object1":[ { "data1":19.77, "data2":-0.953125, "data3":-0.265625, "id&qu ...

Retrieving data from Google Places API in JSON format

Having some trouble with the Places API, I initially attempted to use $.ajax from jQuery but kept encountering an unexpected token error on the first element of the file. It turns out that JSONP cannot be fetched from the Places API. Below is a snippet of ...

What is the best way to divide a string that includes commas into separate parts?

When splitting input strings by commas using .split(','), I encountered an issue with strings that contain commas within a single name. For example: "John, Smith". Typically, my strings appear like this: "Emily, Sasha Flora, Camille-O'neal" ...

Best method for retrieving JSON information from the internet using an API

Looking to work with a URL like this: http://site.com/source.json?s= My goal is to develop a Python class that can take in the "s" query, send it to the specified site, and then extract the JSON results. I've made attempts at importing json and set ...

Steps to display content post authentication using JWT

Utilizing Nodejs and Express for application development. Utilizing JWT for authentication. I have successfully implemented the JWT-based authentication system and tested it with Postman. However, I am facing an issue when passing the request through the ...

Discover the position of a div relative to another div using ng-drag-drop

I'm currently working on a web application that allows users to create their own identity cards. For this project, I am incorporating the ng-drag-drop library from https://www.npmjs.com/package/ng-drag-drop. The main goal is to obtain the coordinate ...

Create a basic search functionality in an Express Node.js application

Recently, I decided to work on a project to enhance my coding skills. I wanted to create a simple search functionality where the URL would be "/search/(parameter here)" and display products whose names match the parameter. After writing a middleware for t ...

Is it possible to convert checkbox values from a form into a JSON format?

HTML snippet : <form class="form-horizontal" id="addpersons" style="padding:20px;"> <fieldset class="scheduler-border"> <!-- Form Title --> <legend class="scheduler-border">Information</legend> <!-- First Name input-- ...

"Enhance your online shopping experience with a React.js popup modal for

In the midst of developing a shopping cart, I find myself facing a challenge in making the modal pop up when clicking on the shopping cart icon. The semantic-ui documentation for modals has not provided clear instructions on achieving this functionality, s ...

Linq has identified a circular reference

Experiencing the following issue while attempting to define a relationship where 1 post can have multiple postComments An error message stating "A circular reference was detected while serializing an object of type System.Collections.Generic.List`1[[DAO ...

The functionality of findDOMNode is no longer supported

My website, built using React, features a calendar that allows users to select a date and time range with the help of the react-advanced-datetimerange-picker library. However, I encounter some warnings in my index.js file due to the use of <React.Stric ...

Finding the total number of nodes within a JSON string is a straightforward process that involves analyzing the

Can the number of nodes in a JSON be calculated using SQL? { "File":[ { "ID":1, "Fragment":"Frag1" }, { "ID":2, "Fragment":"Frag2" }, { "ID":3, "Fragment":"Frag3" }] } Is it possible to determine the ...

Is it possible for .getElementByClassName to identify Ajax.GET elements?

I've run into a problem that I need help with: The issue arises when I have an API that makes an Ajax GET request. In the success function, it creates a button, a div, and several span elements with information inside, each with its own class. The GE ...

JQuery table sorter is unable to effectively sort tables with date range strings

I am facing an issue with sorting a column in my table that contains text with varying dates. The text format is as follows: Requested Statement 7/1/2014 - 9/16/2014 When using tablesorter, the sorting does not work properly for this column. You can see ...

Guide on transferring a file to Node.js using FormData and receiving a confirmation response from Node

Hello, I'm currently working on a basic form where I'm attempting to send a file to my Nodejs server using the FormData object. However, I'm facing an issue as my Node server does not seem to receive the file. Additionally, I would like to k ...

Problem with transferring data from Google Forms to Google Sheets using Google Apps Script

Currently, I am having an issue with my code that adds responses to a Google Sheets from a Google Forms sheet. The problem is that it always adds the responses to the first column, even if it should go into a different column based on its title. I suspec ...