A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below:

<template>
  <div>
    <h1>My Test App</h1>
    <button v-on:click="getHockeyData">Get Team Data</button>
   <div v-for="hockeyData in hockeyDataList" :key="hockeyData.id" >
     <p>{{ hockeyDataList.teams[0].roster.roster[1].person.fullName }}</p>
    </div>
  </div>
</template>


<script>
import axios from 'axios';

export default {
  name: "Weather",
  data() {
    return {
      hockeyDataList: []
    };
  },
  methods: {
   getHockeyData() {
      axios.get("https://statsapi.web.nhl.com/api/v1/teams/21?expand=team.roster").then(response => (this.hockeyDataList = response.data));
    }
  }
  
};


</script>

If you're struggling with incrementing within the loop, where roster[1] needs to be incremented until there are no more instances, turn to Vue's v- commands for guidance. Any assistance or insights on this matter would be highly valued!

Answer №1

To properly iterate over the data, it is essential to start with teams since the JSON structure follows that hierarchy.

Check out the sample using different sections of the JSON, refer to the file for additional details.

<div v-for="team in hockeyDataList.teams" :key="team.id">
  <h1>{{ team.name }}</h1>
  <div>{{ team.venue.name }}, {{ team.venue.city }}</div>
  <div>Established in: {{ team.firstYearOfPlay }}</div>
  <div>Division: {{ team.division.name }} - Conference: {{ team.conference.name }}</div>

  <h2>Roster</h2>
  <div v-for="player in team.roster.roster" :key="team.id + '-' + player.person.id">
    <h3>{{ player.person.fullName }}</h3>
    <div>
      Number: {{ player.jerseyNumber }} - Position: {{ player.position.name }} {{ player.position.type }}
    </div>
  </div>
</div>

Answer №2

<div v-for="team in hockeyDataList.teams" :key="team.id" >
 <p v-for="roster in team.roster.roster :key="roster.id">
   {{ roster.person.fullName }}
 </p>
</div>

If you feel like it, you can also include the index in a v-for loop:

<div v-for="(team, index) in hockeyDataList.teams" :key="team.id" >
 <p>
   {{ hockeyDataList.teams[index].roster.roster[1].person.fullName }}
 </p>
</div>

Answer №3

When using v-for, the index is automatically incremented for you. However, a problem arises when the API returns JSON instead of an array that we can iterate on. By analyzing the API response, it becomes clear that 'teams' is the array we should be iterating on.

<v-for="(team, i) in hockeyDataList.teams" :key="i">

The index increments automatically until reaching the end of the list, allowing us to then iterate through the roster.

<v-for="(roster, j) in team.roster.roster" :key="j">

Combining all these elements together:

<div v-for="(team, i) in hockeyDataList.teams" :key="i">
  <div v-for="(roster, j) in team.roster.roster" :key="j">
    <p>{{ hockeyDataList.teams[i].roster.roster[j].person.fullName }}</p>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I update a specific element within an array of objects in JavaScript based on its reference rather than its index position?

I am dealing with multiple arrays of objects x=[ {a:1}, {b:2}, {c:3}, {d:4} ] y=[ {e:5}, {f:6}, {g:7}, {h:8} ] (etc) and I have a list of references pointing to the objects I need to replace. Instead of having an index into the array, I hold reference ...

Transfer the layout from one HTML file to multiple others without the need to retype the code

I am working on developing an e-commerce website with HTML/CSS. My goal is to have a consistent template for all product pages that are accessed when clicking on a product. However, I do not want to manually code each page using HTML and CSS. Is there a mo ...

rearrange results in ng-repeat based on specified array in AngularJS

Currently delving into Angularjs and have a quick query: I recently received an array from a user which looks like this: userPreferences = [7,5,4] Additionally, I am working with an object that uses ng-repeat to showcase various news items. The object s ...

How do I create more space in Vitepress to prevent the text from feeling cramped and allow it to display in a larger area?

Below is the content of my index.md file: --- # https://vitepress.dev/reference/default-theme-home-page layout: home hero: name: "TP2" text: "Analyzing the code of TP2 by Breno Mazzali Medeiros Tomazelli and Philippe Bouchard" ta ...

Retrieving the selected dates from the Vuetify Datepicker range

Hello everyone at stackoverflow, I have a specific question regarding the vuetify datepicker - how can I retrieve each individual selected date when the range (https://vuetifyjs.com/en/api/v-date-picker/#props-range) prop is enabled? Below is the code fo ...

Create a VueJS/VuetifyJS implementation inspired by the WhatsApp swipe between tabs animation

Currently, I am utilizing the VuetifyJS framework for VueJS and I am interested in replicating the swipe between tabs transition seen in WhatsApp for Android. In WhatsApp, you have the ability to swipe left or right to view a new section as you swipe. Vue ...

Using a global variable to change the class of the <body> element in AngularJS

I've recently developed an angularJS application. Below is the index.html <html ng-app="MyApp"> <head> <!-- Import CSS files --> </head> <body class="{{bodylayout}}"> <div ng-view></div> < ...

"Using the push method in JavaScript allows for the combination of arrays rather than

Looking to retrieve data from an API and store it in an array. When I assign the value directly using '=', the desired data is displayed. However, when attempting to add elements using 'push', they are added as another array. Below is ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

Utilize jQuery setInterval to dynamically add and remove classes on elements

My goal is to display my image in a way that resembles waving flames. I decided to achieve this effect by using two layers (flame tongues) stacked on top of each other in the same position. My initial approach was to hide one flame tongue while showing the ...

The input box is not properly filled with the complete string using protractor sendKeys

[HTTP] --> POST /wd/hub/session/ffcd7072-9f96-45cb-a61d-ec53fc696b56/element/0.9513211246393813-32/value {"value":["1","0","0","0","1"],"text":"10001"} My JavaScript code snippet: this.zipcode = element(by.model('personalInfo.zipcode')); t ...

Unique button for custom "CODE" in Froala

Looking to create a custom button with functionality similar to bold (B) but for source code (Src). I have attempted the following, however it is not fully functional: $("#elm1").editable({ inlineMode: false, minHeight: 300, buttons: ["src"], c ...

differentiating between user click and jquery's .click() method

There are <a href=".. tags on a page with an inline onclick attribute. If a user clicks one without being logged in, they will be prompted to log in. After logging in and the page refreshes, jQuery will trigger .click() on the <a> element to redir ...

VBA: Creating an Array to Store Variable Names

In my current macro, I have a system where rows are copied from one main worksheet to several other worksheets based on specific rules. Not every row is copied to every worksheet, so I use counters for each worksheet to keep track of which rows have been c ...

Unable to retrieve parameter while making a POST request

Need some help with attribute routing. I'm having trouble getting parameters from the HTTP body. The ConnectionID Class includes a property named CValue. $('#btn').click(function () { $.ajax({ type: "POST", url: "http:// ...

Tips for organizing nested arrays in PHP based on the sixth index timestamp

I am a newcomer to PHP multi-dimensional arrays and I am seeking a 100% functional solution, please... I have attempted to use the array_multisort and usort functions, but they are not yielding the desired results for me. Frankly, I am unsure of how to ap ...

Working with MySQL fields in Laravel: Adding and fetching data

Currently, I am experimenting with a JSON field and facing some challenges. In my Customer model, I have added: protected $casts = [ 'billingConfig' => 'array' ]; To update a test field in my controller, I used: $custom ...

Analyzing string values in Cypress

When attempting to compare two values within a page and make an assertion, my goal is to retrieve the value of one text element and compare it with another value on the same page. While I find this process straightforward in Java/selenium, achieving the ...

Unable to access the 'fn' property of undefined in Handlebars causing a TypeError

I encountered an issue with my custom handlebars helper. When I fail to define values for the parameters, I receive the following error message. module.exports = function(src, color, classatr, options) { if (typeof src === 'undefined') src ...

Guide on transforming a PHP array encoded in JSON into a JavaScript array

After fetching a JSON encoded array via AJAX from a PHP file, I need to manipulate it as an array in JavaScript. How can I achieve this? Here is my AJAX call to the PHP File: $.ajax({ type:"POST", url:"ajaxfetch.php", success:function(re ...