Home > Mobile >  How can I get all values returned from api? Javascript
How can I get all values returned from api? Javascript

Time:12-26

I'm trying to fetch API data and insert it in a table ( I am using VS code and live server). So far I've got the right data from the ApI and my thought is to loop that data and send it. When I try to loop the data I only get the last football match sent - Why don't I get all 13 games? I need some advice or suggestions on how to succeed.

    export function getMatchData() {

   return fetch('https://stryk.herokuapp.com/strycket2022')

.then(function (response) {

  return response.json();

})



.then(function (data) {


  let gameArray = data.playedGames;
  let gameInfo = "";

  for (let i = 0; i < gameArray.length; i  ) {


    gameInfo = data.playedGames[i].teams[1].name   " VS "   data.playedGames[i].teams[2].name;



  }
  console.log(gameInfo);



  return gameInfo;






});

CodePudding user response:

create empty array or object instead string. i'm about variable gameInfo. and on each interation you have to add new value (gameInfo.push(value) if it will be array, for example). so you will get array that contains information about each item. you will able to use it for your goals

in your vaiant you rewriting value in gameInfo on every interation and at the end of loop you are getting only last value

CodePudding user response:

Maybe this will help to get you on the right track?

fetch('https://stryk.herokuapp.com/strycket2022')
 .then(response=>response.json())
 .then(function (data) {
   let gameArray = data.playedGames;
   let gameInfo = [];
   for (let i = 0; i < gameArray.length; i  ) {
     gameInfo.push( data.playedGames[i].teams[1].name   " VS "   data.playedGames[i].teams[2].name);
   }
   console.log(gameInfo.join("\n"));
});

Or, even shorter:

fetch('https://stryk.herokuapp.com/strycket2022')
 .then(r=>r.json())
 .then(dat=>console.log(dat.playedGames.map(g=>g.teams[1].name " vs " g.teams[2].name).join("\n")));

CodePudding user response:

const res = await fetch('https://stryk.herokuapp.com/strycket2022')
const data = await res.json();

let gameArray = data.playedGames;
let gameInfo = [];

gameArray.map(game => {
gameInfo.push( game.teams[1].name   " VS "   game.teams[2].name);   
})

console.log(gameInfo);

CodePudding user response:

As already mentioned, You are setting a new value in the gameInfo variable every time, so you only see the last value Try creating an array and pushing the value there Here's an example:

  fetch('https://stryk.herokuapp.com/strycket2022')
 .then(response => response.json())
 .then(function (data) {
    const gameArray = data.playedGames;
    let gameInfo = [];

    gameArray.ForEach((game) => {
        const newGame = game.teams[1].name   " VS "   game.teams[2].name;
        gameInfo.push(newGame);

    });
    
    console.log(gameInfo);
    
    return gameInfo;
 });
  • Related