Home > front end >  How to retrieve variable from multi-level array - Vue.js
How to retrieve variable from multi-level array - Vue.js

Time:11-17

I'm just doing a practice project in Vue.js, I'm going to loop through a team page from the NHL and output the name of each player.

I've got an API endpoint here; https://statsapi.web.nhl.com/api/v1/teams/21?expand=team.roster

I'm trying to traverse through the levels but am getting "lost" at the roster. I can output the whole roster but can't seem to drill any further down than that.

I'm storing the contents of the entire JSON response in a variable called "hockeyData".

This is what I'm using to output the roster (this works)

{{ hockeyData[0].roster }}

Now when I try to get the player names, I'm doing this and it doesn't work

{{ hockeyData[0].roster.roster[0].person.fullName }}

I'm sure it's something simple but try as I might I'm just not getting the name to output.

Any help is greatly appreciated!

CodePudding user response:

Try using computed like

{{ getRoasterData }}

and

computed: {
 getRoasterData() { 
  return this.hockeyData[0].roster.roster[0].person.fullName;
 }
}

CodePudding user response:

Here's a working example on Codepen based on your data.

You haven't posted any code so I can't be sure, but your issue could be a timing issue. Make sure the values are available at the time of requesting from the template.

I have an v-if in my example around the data that checks if the data is available (for example purpose, I'm only checking if the roster is available, I should check for all children, but it's an example..).

    <div v-if="roster && roster.length">
        First: {{ roster[0].person.fullName }}
    </div>
  • Related