Search code examples
javascriptfor-of-loop

In JS how do you access the next "object" in a for...of loop


I'm basically trying to build a site that shows data from an API. I use the following Async function to get the data:

async function getapi(url) {
   //store response
   const response = await fetch(url);
   
   //store data in JSON
   var data = await response.json();
   getData(data);
}

In my getData function, I have have the following:

for(let r of data.rounds) {
  let round = r.names.shortName;
  let nextRound = //no idea how to get the name of the next round

This returns the round that I'm currently in (R1 in the first loop). Essentially what I want is the next rounds shortName. (so I want R2 in the first loop). Is there any way to access the next loop's data?

console.log(r) shows: console.log of R


Solution

  • Use for loop instead of forof loop. It alows you to check next index of the array and use it as below.

    for (let i = 0; i < data.rounds.length; i++) {
        const round = data.rounds[i];
        const name = r.names.shortName;
        let nextRound =  data.rounds[i + 1];
        if (nextRound) {
            // your code here
        }
    }