0

I am using jQuery and got an response from API by using $.ajax. I want to grab the Arrays length from inside each object and display that in the html page. This is what I have done so far. Here is the API response, i did breakdown of the last object, which contains an array and player names:

{_type: "InjuredPlayers", flaggedTokens: Array(1)} //1 injured player name
{_type: "InjuredPlayers", flaggedTokens: Array(3)} //3 injured players names
{_type: "InjuredPlayers", flaggedTokens: Array(5)} //5 injured players names
{_type: "InjuredPlayers", flaggedTokens: Array(2)} //2 injured players names
>flaggedTokens:Array(2)
 >0:{offset: 0, token: "John", type:"UnknownToken"}
 >1:{offset: 1, token: "Adam", type:"UnknownToken"}
 length: 2
 >_proto_:Array(0)
 _type: "InjuredPlayers"
>_proto_: Object

In order to grab the length of the Array I can do any of these 2 methods according to this Get length of array inside object

console.log(response.flaggedTokens.length)
1
3
5
2

OR

console.log(response["flaggedTokens"].length)
1
3
5
2

My Failed Attempts: I assigned this output to a variable and tried to loop through and output by doing this:

$.ajax(gameResponse).done(function(response) {
 let injuredPlayers = response.flaggedTokens.length;
 let injuredPlayersArray = [];
 for (let i = 0; i < injuredPlayers.length; i++) {
 injuredPlayersArray.push(injuredPlayers[i])
 }
 $('.injured_players').html(injuredPlayersArray[i])
})
<div class="container">
Team One Total number: <span class="injured_players"></span> //should be 1
Team Two Total number: <span class="injured_players"></span> //should be 3
Team Three Total number:<span class="injured_players"></span> //should be 5
Team Four Toal number: <span class="injured_players"></span> //should be 2
</div>

Clearly I made some mistake which I can't seem to figure this out by myself. I was hoping if someone can guide me through the right direction.

asked Dec 15, 2021 at 21:11
11
  • Why are you returning inside the for? Commented Dec 15, 2021 at 21:14
  • 1
    $('.injured_players').html(string) will set the HTML of the first element with the class "injured_players" to the given string. Move that line of code inside the for loop and make it $('.injured_players').eq(i).html(string). Remove the return line because that exits the function immediately. Commented Dec 15, 2021 at 21:24
  • Also, you should be getting errors in your console. injuredPlayers is a number, and numbers don't have a length property, so you should get an error on i < injuredPlayers.length. Commented Dec 15, 2021 at 21:27
  • 1
    @HereticMonkey No that wouldn't be an error, (5).length is just undefined, and i < undefined is just never true. Commented Dec 15, 2021 at 21:28
  • 1
    eq(i) gets the element at the index i. .html(string) sets the HTML to whatever string is. Commented Dec 15, 2021 at 21:31

1 Answer 1

0

To start with, in your for loop, you are returning the push action, but that's unnecessary and it kills the loop on the first iteration. Also, you have already set the length of the array to a new variable, but then in your for loop, you try to get the length of the new variable. Lastly, you declare injuredPlayersArray in your ajax statement, but based on your post, you recieved 4 separate api responses, so it should be declared outside of your ajax call so that the array doesn't get overwritten with every new call. And you don't need a for loop as you're only working with one array. Here is what it should look like.

let injuredPlayersArray = [];
$.ajax(gameResponse).done(function(response) {
 let injuredPlayers = response.flaggedTokens.length;
 injuredPlayersArray.push(injuredPlayers)
})

Your other mistake is that you are trying to dynamically display the value in the proper html tag, but you're setting the value for every span tag at the same time. So after your loop is finished, they would all say 2.

To fix that you can add a for loop after all of your api calls are completed (aka NOT inside a $.ajax().done()):

for (let i = 0; i < injuredPlayersArray.length; i++) {
 $('.injured_players').eq(i).html(injuredPlayersArray[i])
}

Note: .eq() returns a set of DOM elements that match the selector it is called upon. So $('.injured_players') matches 4 elements on your page and in your for loop, it finds the i-th element in that set (so index 0 is equal to the first span tag) and sets the html for that element.

Note 2: There is an assumption I had to make with your api calls. From the way your api call is storing the length of the flaggedToken array in your response, it seems each ajax response returns a single object with the array of injured players and that you will have 4 separate api calls. However, if that's not the case and the response returns a array of objects, you will need to iterate over the array and get the length for every array in every object one at a time. You can also then ignore my suggestion to move the declaration of injuredPlayersArray to outside the api call. And the second for loop i wrote would go inside the api call.

answered Dec 15, 2021 at 22:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.