Home > OS >  .push() is not working outside of the for loop
.push() is not working outside of the for loop

Time:05-30

I have already handled a response from an API call. I then export the data into a function that i'm using a for loop inside. The const diomerda is passed to the ejs file where i am outputting the array data from the API. However the data in the array is over 5000 entries, so i want to run a for loop to populate the ejs file with the entire array. But when I use loop.push it does not populate the const loop. console.log(loop) just reads [].

Once the const loop = [] is populated with the array i was then going to pass the data into the const diomerda = [json.entries[loop].character.name]

I'f anyone has any other ideas on how to acheive what i'm trying to do then please feel free to send away. Thanks in advance.

    .then(response => response.json())
    .then(json => ejsoutput(json))
}

function ejsoutput(json) {
    const loop = []
    console.log(loop)
    const diomerda = [json.entries[0].character.name, json.entries[1].character.name, json.entries[2].character.name]
    for (var i = 0; i < json.entries.length; i  ) {
        loop.push(i)
    }
    res.render('index', {
        leaderboard: diomerda
    })
}
});

CodePudding user response:

Once the const loop = [] is populated with the array i was then going to pass the data into the const diomerda = [json.entries[loop].character.name]

If what you want is to populate diomerda with each character name return from the api, do this

function ejsoutput(json) {
    const diomerda = [];
    for (var i = 0; i < json.entries.length; i  ) {
        diomerda.push(json.entries[i].character.name);
    }
    console.log(diomerda);
}

OR in simpler terms

function ejsoutput(json) {
    const diomerda = json.entries.map(item => item.character.name);
  
    console.log(diomerda);
}

CodePudding user response:

To debug, print (log) the json object, instead of the empty loop array (shoule get you on track).

Json should be a promise. That's probably what you're running into. See: https://developer.mozilla.org/en-US/docs/Web/API/Response/json

Try something like

json().then(function(json) {
      
});
  • Related