Bruno Bueno
Bruno Bueno

Reputation: 1

JavaScript looping through an array inside a object inside an array

I have a list of games(objects) inside a object, which is inside an array of players. I'm trying to check which object inside the array is the current user to than go in the games array and a print out the objects property.

Go through PlayerList to find currentUsers

for (let i = 0; i < model.playerList.length; i++) {
        if (model.currentUser == model.playerList[i].userName)
        //Go Through games from the player to print the game information
        {
            for (let i = 0; i < model.playerList[i].game.length; i++) {
                html += `<div>
           <p> Spillnr: ${model.playerList[i].game[i].gameNumber}</p>
           <p> Ord: ${model.playerList[i].game[i].word}</p>
           <p> Dato: ${model.playerList[i].game[i].date}</p>
           <p> Forsøk: ${model.playerList[i].game[i].attempts}</p><hr>
            </div>`;
            }
        } else { console.log('ok') }

I'm getting the properties of game from different objects inside playerList instead of only getting from the currentUser.

HELP PLEASE

Upvotes: 0

Views: 88

Answers (1)

Prdufresne
Prdufresne

Reputation: 296

I think the root of your issue is that you're using the same index i for both the playerList and game arrays. When you change i to go through the games, you're also changing which player you're getting information from.

I'm guessing your for loop was intended to iterate through the list of games, not the list of players, so before you can run that loop, you need to find the player in the playerList

I would recommend using find()

// Find the player with the username that matches currentUser
// If the player is found, thisPlayer will contain the player object
let thisPlayer = model.playerList.find(player => model.currentUser == player.userName);

// If we fould a player, iterate through the games and add HTML for each one
if(thisPlayer) {
    thisPlayer.game.forEach((game) => {
        html += `<div>
        <p> Spillnr: ${game.gameNumber}</p>
        <p> Ord: ${game.word}</p>
        <p> Dato: ${game.date}</p>
        <p> Forsøk: ${game.attempts}</p><hr>
         </div>`;
    })
}

Upvotes: 1

Related Questions