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

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

JavaScript method to prevent users from entering numbers as the first two characters, with all subsequent characters being numbers only

I need a specific requirement for my form. The textbox field in my form is labeled "DEA License number", and I want it to only allow the user to enter alphabetic characters for the first two characters, followed by numbers afterward. I am looking to impl ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...

Updating a calendar page in Rails 4 using AJAX technology

Currently, I am utilizing jQuery's datepicker functionality to display a calendar. The intended behavior is that upon clicking on a specific date, the page should generate relevant information (in this case, a table showcasing available seating) assoc ...

Why is React JS unable to discover my exported modules?

Upon running my React app, the console displayed the following error message: Failed to compile. ./src/components/login/index.js Attempted import error: 'Login' is not exported from './login'. Here is an overview of the folder struct ...

Utilizing React and MaterialUI to create a dynamic GridLayout with paper elements

I am using the react-grid-layout library to create a dynamic grid where each item is a paper component from the React Material UI. However, I encountered an issue while running the application. The browser displayed the error message: "TypeError: react__W ...

Issues with Vue Carousel Sliding Functionality

I'm currently tackling a project that involves incorporating Vue Carousel for displaying product slides with both images and text on each slide. My goal is to have only 5 slides displayed per page, complete with navigation arrows and the ability to dr ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Mapping JSON data with an elastic search cluster can be challenging, especially when dealing with a dynamic number of fields

I am currently developing an application where I need to map JSON data for storage in Elasticsearch. The challenge is that the number of fields in the JSON data is dynamic. How can I handle mapping in this scenario? Mapping Snippet var fs = uploadedFiles ...

What are some techniques for styling a field when the div id is not specified?

I need to customize a data field within a table, but I am unable to locate or identify its div ID. Here is the page source: <tbody> <tr> <td style="font-size:12px; text-align:center;" name=""> <div sty ...

Server crashing as nodemon encounters mongoose issue

Currently, I am in the process of learning Node JS, Mongodb, and Express JS. My goal was to create a database using Mongodb Compass and store some data within it. However, every time I attempt to run my code, my nodemon server crashes after a few minutes o ...

Validation of the existence of a MongoDB user

I'm currently working on implementing a sign-up form using Mongo, Node.js, and Express.js. I've managed to successfully insert a document into the users collection for a new user. However, I now need to set up validation to check if a user alread ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

PHP's for loop may not iterate through the entire array

I am currently using PHP/7.2.0beta3 and I have a requirement to develop a custom function in PHP that can reverse an array. For example, if the array is (1,2,3), the desired outcome should be (3,2,1). My initial approach was to utilize the array_pop funct ...

Looking for a drum set with clickable buttons? Having trouble changing the background color in CSS/HTML? Wondering how to map keyboard keys to HTML buttons?

Behold my HTML creation: <H1> <center> EPIC GUITAR JAM </center> </H1> <img class="guitar" src="guitar.jpg" /> <button class="strum" onclick="Strum()"> Strum Chord </button> <button class="pluck" o ...

Tips for displaying a div near the cursor's location when hovering in React JS

Looking for a way to show a hidden div at cursor position when hovering on Text item1 or item2. Check out the sample GIF animation in this Link My attempt using Jquery code inside React resulted in an error: $(".text-item").mouseenter(function ( ...

Using Jquery to insert content into HTML using the .html() method is not possible

I am inserting Dynamic Code into a Div via Ajax and I also need to include some Javascript, but it's not displaying in the code. Below is the code snippet: $.ajax({ url: "ajax_add_logo_parts.php", data: 'act=getPartIm ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

Learn the steps for inserting or updating data in a local JSON file solely through JavaScript

Currently, I am in the process of reading a JSON file and removing an element once it finds an exact match. My goal is to then push the remaining data back into the JSON file after deletion. readJsonFile("./objects.json", function(jsonData){ let parsedD ...