Tips for utilizing a vue.js nested for loop with two arrays using v-for

The issue has been resolved, and both my parent view and child component code are now correct and functioning properly I am using Vue.js with the goal of iterating similarly to a nested for loop to display a matrix table. Initially, I tried to achieve this by using a nested v-for loop but encountered difficulties in making it work.

The data used to construct the table consists of dates forming a schedule, each retrieved from a schedule collection in MongoDB. Each day, all teams have a match against another team, and the match data for each team is stored in a schedule array within each document.

To simplify the process and accomplish this task, I created a schedule table containing all team schedules in the parent view, which I passed as a property to the child component to streamline the v-for coding.

The logic for what I'm aiming to do in the child component follows a traditional pattern:

for(const i=0; i<schedules.length; i++) {
for(const j=0; j<weeks.length; j++) {
  console.log("This match is " + schedule[i] + " on " + week[j]) 

I attempted two strategies in the child component without success:

1.) Wrapping a v-for inside a div:

<div v-for="(schedule,j) in schedules" :key="j">
        <sui-table-cell v-for="(number, i) in weeks" :key="i">
        {{schedules[schedule][i].team}}
        </sui-table-cell>
</div>      

2.) Wrapping a v-for inside a template (this code does not compile):

<template v-for="schedule in schedules">
        <sui-table-cell v-for="(number, i) in weeks" :key="i">
        {{schedules[schedule][i].team}}
        </sui-table-cell>
</template>    

The expected data should resemble the image below (click on the link to see where I encounter issues with iteration):

Correct View Of Data

Parent view template.

<template>
  <div>
    <h1 class="ui header center aligned">ACL</h1>
    <h4 class="ui header center aligned schedule">
      <em>CRIBBAGE SCHEDULE</em>
    </h4>
    <sui-table id="standings" class="celled table center aligned">
      <inner-table :weeks="totalWeeks" :allPlayers="allPlayers" />
    </sui-table>
  </div>
</template>
<script>
import TableForm from "./TableForm.vue";
import { api } from "../../../helpers/helpers.js";
export default {
  name: "schedule-header",
  components: { "inner-table": TableForm },
  data() {
    return {
      totalWeeks: [],
      allDates: [],
      allPlayers: []
    };
  },
  async mounted() {
    this.totalWeeks = await api.getTotalWeeks();
    this.allDates = await api.getAllDates();
    this.allPlayers = await api.getTeams();
  }
};
</script>
<style scoped>
h4.schedule {
  color: brown;
}
</style>

Child Component:

<template>
  <div>
    <sui-table-header>
      <sui-table-row>
        <sui-table-header-cell></sui-table-header-cell>
        <sui-table-header-cell>TEAMS</sui-table-header-cell>
        <sui-table-header-cell v-for="(number, i) in weeks" :key="i">WK{{i+1}}</sui-table-header-cell>
      </sui-table-row>
      <sui-table-row>
        <sui-table-cell></sui-table-cell>
        <sui-table-cell></sui-table-cell>
        <sui-table-cell v-for="(number, i) in weeks" :key="i">{{ number.gameDate.substring(0,10) }}</sui-table-cell>
      </sui-table-row>
    </sui-table-header>
    <sui-table-row v-for="(player, i) in allPlayers" :key="i">
      <sui-table-cell>{{i+1}}</sui-table-cell>
      <sui-table-cell>{{ player.player1 }}&{{player.player2}}</sui-table-cell>
      <sui-table-cell v-for="(week, j) in weeks" :key="j">{{player.schedule[j]}}</sui-table-cell>
    </sui-table-row>
  </div>
</template>

<script>
export default {
  props: ["weeks", "allPlayers"]
};
</script>

Answer №1

In Vue, the key property is used to distinguish between components and prevent unnecessary rendering. By using :key="i" in your code, Vue interprets all sui-table-cell with the key i as identical, resulting in repeats. To avoid this, it's important to provide unique keys.

Although the code may function as intended, it is not advisable to use the index as a key. It is recommended to implement a more effective keying strategy.

<sui-table-row v-for="(player, i) in allPlayers" :key="i">
      <sui-table-cell>{{i+1}}</sui-table-cell>
      <sui-table-cell>{{ player.player1 }}&{{player.player2}}</sui-table-cell>
      <div v-for="(schedule,j) in schedules" :key="j">
        <sui-table-cell v-for="(number, i) in weeks" :key="`${j}_${i}`">
          {{schedules[j][i]}}
        </sui-table-cell>
      </div>
</sui-table-row>

Sample data:

{
    schedules: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[2,3,4,5,6,7,8,9,1]]
    weeks: [1/1,1/7,1/14,1/21,1/28,2/5,2/12,2/19,2/25,3/3]
}

The solution involving the template will not be effective, as the template portion is never rendered. It is primarily used when utilizing v-for for multiple internal elements like:

<template v-for="...">
 <h1></h1>
 <p></p>
</template>

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

Why am I unable to locate my personalized module?

I've encountered an issue with my npm module not being found in my sample script after publishing it. Here is the link to my module: https://www.npmjs.com/package/kong-hmac https://github.com/y-zono/kong-hmac-js Here's what I have tried: $ m ...

Can you extract information from the XML file and modify the anchor tags?

<description> <div class="field field-name-field-image field-type-image field-label- hidden"><div class="field- items"><div class="field-item even"><a href="/news/news/vg"> ...

Different Zoom feature for JIT Graph

I'm currently working with the Java Infovis Toolkit and I'd like to use buttons for zooming in and out instead of using the mouse wheel. Can someone guide me on how I can implement two separate buttons for Zoom In and Zoom Out functions? ...

Struggling with React Js and need some assistance?

I'm completely new to React Js and encountering issues with my code. Here's what I have: Here is the content of my script file named Main.jsx. This file gets compiled by React, and the output is stored in main.js under the 'dist' folde ...

Using JavaScript with namespaces in C#

I am currently trying to explore AJAX and web services through self-teaching using C# and JavaScript. After doing some research on Google, it seems like I might be facing a namespace problem. Here is the snippet of my code: using System; using System.Col ...

Getting the current URL in InApp browser on Phonegap 3.0: A quick guide

Hey there, I am having trouble retrieving the current URL of an in-app browser when clicking the close button or at any time after loading a URL. Here's my code: var ref = window.open('http://google.com', '_blank', 'hidden=y ...

Guide to integrating WordPress into a subpage of a Nuxt.js website

I'm currently working on a project in nuxtjs 2, deployed on vercel. Additionally, I have a web server that hosts my WordPress site. Is there a way to integrate a WordPress WooCommerce store into my nuxtjs website? Specifically, I would like to create ...

Pictures in the portfolio failing to load on Mozilla Firefox

Having some trouble with my WordPress website bmfconstruction.com.au/new/. In the project section, all images are loading correctly in Chrome, Opera, and IE. However, when it comes to Firefox, none of the images seem to be showing up. I've tested this ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

What is the best way to save longitude and latitude coordinates in a database using the <input> method?

Learn how to use HTML code <html> <body> <p>Press the button below to receive your coordinates.</p> <button onclick="getLocation()">Get Coordinates</button> <p id="demo"></p> <script> var x = doc ...

The presence of parentheses in a JQuery selector

My database contains divs with ids that sometimes have parentheses in them. This is causing issues with my JQuery selector. How can I resolve this problem? Let me provide an example to illustrate: https://jsfiddle.net/2uL7s3ts/1/ var element = 'hel ...

What is the best way to ensure that this <span> maintains a consistent width, no matter what content is placed inside

So here's the deal, I've got some dynamically generated html going on where I'm assigning 1-6 scaled svgs as children of a . The span is inline with 2 other spans to give it that nice layout: I want these "boxes" to all be the same width be ...

Steps to create a clickable button wrapper label in React

Contained within the components below: <CheckboxGroupLabel htmlFor={option.label}> <FormCheckbox onClick={() => onChange} key={option.label} defaultChecked={defaultChecked} {...rest} /> {option.value} ...

Error: Trying to play the Snake Game with the P5.js Library, but getting the message "(X)

During my journey of coding a snake game by following a tutorial, I encountered an issue that the instructor had not faced before. Strangely enough, I am unable to identify the root cause of this problem. To aid in troubleshooting, I meticulously commente ...

Is the auto-import feature in the new VSCODE 1.18 compatible with nodelibs installed via npm?

Testing out the latest auto-import feature using a JS file in a basic project. After npm installing mongoose and saving an empty JS file for editing, I anticipate that typing const Schema = mongoose. will trigger an intellisense menu with mongoose nodelib ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

Acquire the selected option's value and display it within a div container

Is there a way to extract and display only the price value (after the " - ") within a div with the id of "price", updating as the select element is changed? <select id="product-select" name=""> <option value="1">Product Name / Yellow / S - ...

Implementing Github Oauth2 in a Rails server independent from a chrome extension

Looking to implement Github Oauth2 from my chrome extension, but rather than using chrome.identity.launchWebAuthFlow I want to handle it through my server. This way, I can avoid exposing my client ID and Client Secret in the javascript of the extension. My ...

Exploring and identifying matching pairs within a JavaScript object

Currently, I have a JavaScript object that looks like this: records: [ { id: 1, name: michael, guid: 12345 }, { id: 2, name: jason, guid: 12345 }, { id: 3, name: fox, guid: 54321 }, { id: 4, ...