Ways to retrieve a specific attribute within a detailed JSON reply

I have implemented cloud code in ParseServer - Back4app, which utilizes node.js to send a request for Football API. The axios request returned the following result:

{
    "result": {
        "get": "teams",
        "parameters": {
            "country": "brazil"
        },
        "errors": [],
        "results": 785,
        "paging": {
            "current": 1,
            "total": 1
        },
        "response": [
            {
                "team": {
                    "id": 6,
                    "name": "Brazil",
                    "code": "BRA",
                    "country": "Brazil",
                    "founded": 1914,
                    "national": true,
                    "logo": "https://media.api-sports.io/football/teams/6.png"
                },
                "venue": {
                    "id": 204,
                    "name": "Estadio Jornalista Mário Filho (Maracanã)",
                    "address": "Rua Professor Eurico Rabelo, Maracanã",
                    "city": "Rio de Janeiro, Rio de Janeiro",
                    "capacity": 78838,
                    "surface": "grass",
                    "image": "https://media.api-sports.io/football/venues/204.png"
                }
            },
            {
                "team": {
                    "id": 118,
                    "name": "Bahia",
                    "code": "BAH",
                    "country": "Brazil",
                    "founded": 1931,
                    "national": false,
                    "logo": "https://media.api-sports.io/football/teams/118.png"
                },
                "venue": {
                    "id": 216,
                    "name": "Arena Fonte Nova",
                    "address": "Rua Lions Club, Nazaré",
                    "city": "Salvador, Bahia",
                    "capacity": 56500,
                    "surface": "grass",
                    "image": "https://media.api-sports.io/football/venues/216.png"
                }
            }, (repeat for more 783 X)

What is the most efficient way to loop through the response data and extract all "teams" and their corresponding "venues" names, ids, addresses, etc. using JavaScript?

I have attempted various methods, but unfortunately none of them have been successful for me.

Here's an example of my current code:

Parse.Cloud.define("teams", (request)=>{
  const axios = require("axios");
  const time = request.params.time;
  const options = {
    method: 'GET',
    url: 'https://api-football-v1.p.rapidapi.com/v3/teams',
    params: {country:'brazil'},
    headers: {
      'X-RapidAPI-Key': 'd69302225emshdf770c890926efdp19ca04jsn08d2244e2253',
      'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
     }

  };
      var resultado = axios.request(options).then( function (response) {
        return (response.data);
      //  return "olá função "
    }).catch(function (error) {
         return("erro meu nobre!");
});

return resultado;

Answer №1

// Using the axios library to make a GET request to fetch information about teams from Brazil
const options = {
  method: 'GET',
  url: 'https://api-football-v1.p.rapidapi.com/v3/teams',
  params: {
    country: 'brazil'
  },
  headers: {
    'X-RapidAPI-Key': 'd69302225emshdf770c890926efdp19ca04jsn08d2244e2253',
    'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
  }
};
// Making the request and handling the response
const resultado = axios.request(options)
  .then(function(response) {
    const data = response.data.response 
    // Looping through the data for each team and venue
    data.forEach(function(team) {
      console.log(team) // Logs the "team" and "venue" objects for each team
    })
  })
  .catch(function(error) {
    return ("Oops! Something went wrong!");
  })
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

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

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

Tips for generating a server error during the retrieval of JS files

I'm a beginner in JavaScript and I've been given a task to send an email input from a form to a node server. Everything is working correctly, but there's one requirement I need to implement: Whenever the entered email is [email protec ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

Decoding JSON to extract nested dictionaries in Python

My json file contains an object with a dictionary nested within it: { "__class__": "monster", "name": "Mugger", "level": 1, "hpTotal": 20, "attacks": ["Sword", "Knife"], "stats": { "AC": 12, "STR": 11, "DEX": 12, ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

Tips for transferring information from an express rendering to a Vue component?

When working with an express route, page.js router.post('/results', (req, res, next) => { output.terms = "hello" output.results = [{"text": "hello world"}, {"text": "hello sunshine"}] res.render("/myview",output) }) The cod ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...

What is the best way to include a new class into the current class in this particular scenario?

Just starting out with Javascript and Jquery, so please bear with me if this question seems basic I'm dynamically constructing HTML like this: var favoriteresultag = '<ul>'; favoriteresultag += "<section id='"+name+"' ...

I'm encountering a persistent issue of receiving null when attempting to read a JSON object file in

Every time I attempt to read, the result is always null. This pertains to a json file. { "team": { "name": "john 1", "id": "12345" } } I am attempting to accomplish this using POJO. public class Team { private String name; private ...

Learning how to interpret input from the command line in Vertx

Would appreciate some guidance on how to read command line arguments in vert.x using JavaScript. For instance, I am wondering how to go about reading: arguments(arg1, arg2, arg3) vertx run example.js arg1 arg2 arg3 ...

Utilizing Literal and Instance Formats in JavaScript

There are two main methods for creating JavaScript objects. The confusion arises in understanding when to use each notation. Below are examples of both literal and instance variables, each holding different values and producing different results when opera ...

JavaScript not functioning properly for the Sibice challenge on Kattis

Currently, I am in the process of learning JavaScript and a friend recommended trying out Kattis for solving tasks, even though it might not be ideal for JS. As part of this challenge called Sibice, the goal is to determine if matches will fit into a box. ...

issue with accessing instant state modification via useEffect

I am currently learning about React Hooks While I try to render a list from an array and remove the first element on click, the state gets updated in the handleclick function but it doesn't render correctly export default function App() { const [na ...

Is it possible to search and index nested object keys in JSON using PostgreSQL?

If my database table 'configurations' contains rows with a 'data' column in JSONB format like the example below: { "US": { "1234": { "id": "ABCD" } }, " ...

What is the best way to convert this jQuery code into an AngularJS implementation?

I'm diving into the world of AngularJS and looking for a more elegant solution using AngularJS principles Controller $scope.filter = function($event, active, id) { var html = ""; if(active){ $http({method: 'GET& ...

Tips for transforming numerical date data into a string format

Is there a method to convert the numeric month in a table into a string format? <table style="width: 100%;"> <tr> <th>Date</th> <th>Total</th> </tr> <tr> <td id="date ...

Workaround for syncing MobX observables when toggling a select/deselect all checkbox

In my application, there is a checkbox list with a 'Select All' checkbox at the top. The list is populated by an observable array of strings. When the user clicks on 'Select All', it should check all checkboxes; subsequent clicks should ...

ReactJs - The pagination feature in MaterialTable is malfunctioning, it is not displaying the correct

I am currently utilizing the Material-table plugin. It successfully displays the data, however, I am facing issues with Pagination and Row per Page dropdown functionality. When trying to click on the next button or select a number of rows, nothing happens. ...

Issue locating bug in JSON implementation in AS3

The piece of code I've written is: var el = event.location; var m = el.substr(el.indexOf('?Mess:')+6).replace(/%20/g,' ').replace(/%22/g,'"') ; trace('*** Going to parse: '+m); trace(JSON.parse( m ...

Update the image source every 1 second with Jquery and Javascript

I've been experimenting with creating a script that dynamically changes the source of an image every two seconds based on a list. Essentially, my current approach involves using a for loop to iterate over the provided list: $(document).ready(functio ...