Mastering the correct way to access array index positions in Vuejs

HelloWorld.vue

<template>
  <div>
    <div v-for="(pizza, index) in pizzas" :key="pizza.name">
      {{ pizza.name }}
      <List
        :content="matchingPizza"
        :pname="pizza.name"
        :qname="quantities[index] ? quantities[index].qname : ''"
      />
    </div>
  </div>
</template> 

<script>
import List from "./List.vue";
export default {
  name: "HelloWorld",
  components: {
    List,
  },
  data() {
    return {
      pizzas: [
        {
          name: "chicken pizza",
        },
        {
          name: "chicken pizza special",
        },
        {
          name: "mutton pizza",
        },
        {
          name: "plain pizza",
        },
      ],

      quantities: [
        {
          qname: "one",
        },
        {
          qname: "two",
        },
        {
          qname: "three",
        },
        {
          qname: "four",
        },
        {
          qname: "five",
        },
      ],

      matchingPizza: [
        {
          matchnum: "1",
          availability: "later",
          pname: "plain pizza",
          qname: "five",
        },
        {
          matchnum: "2",
          availability: "buy now",
          pname: "chicken pizza",
          qname: "one",
        },
        {
          matchnum: "3",
          availability: "buy now",
          pname: "plain pizza",
          qname: "five",
        },
        {
          matchnum: "4",
          availability: "buy now",
          pname: "chicken pizza special",
          qname: "five",
        },
        {
          matchnum: "5",
          availability: "later",
          pname: "mutton pizza",
          qname: "five",
        },
      ],
    };
  },
};
</script>

List.vue

<template>
  <div>
    <div v-if="matchingPizza.length > 0">
      <div
        v-for="match in matchingPizza"
        :key="match.matchnum"
        :class="{
          green: match.availability === 'buy now',
          red: match.availability === 'later',
        }"
      >
        <div v-for="quantity in quantities" :key="quantity.qname">
          {{ quantity.qname }}
        </div>
        <div class="next-data-two">{{ match.availability }}</div>
      </div>
    </div>
    <div v-else class="next-data"><p>No availability</p></div>
  </div>
</template>

See my working code here:-

https://codesandbox.io/s/data-display-tcr8oj?file=/src/components/HelloWorld.vue

From the helloworld.vue you can see this line :qname="quantities[index] ? quantities[index].qname : ''"

Where as per the above code, from the quantities array. it is not pointing to the particular index value correctly?.

According to my output from codesandbox:-

For chicken pizza it showing as , chicken pizza --> one --> later But correct path is, chicken pizza --> later --> five

Similarly for others too, having same issue....

Is it because of index position wrong or issue with logic??

Answer №1

Your specified route is chicken pizza --> later --> five.

This path has no connection to the quantitys array. You can directly show the details using the content attribute.

Check out this Functional Demo! https://codesandbox.io/s/data-display-forked-kjxuyv

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

Svelte remains static and is not experiencing re-rendering

I am currently incorporating the history component in Svelte, where it should display when changes occur in the bids array. const bidsArray = [ { player: 0, bidType: 'pass' }, { player: 1, bidType: 'level', level: '1&apos ...

How do I use Vue.js to capture keypress events and update the input value in real-time?

Here is the scenario I am facing: https://codepen.io/anon/pen/WYJopq I have implemented a functionality to track key presses and duplicate the input into another field with the following code snippet: [![methods: { clone: function() { this.m ...

Node.js - Hitting maximum call stack size limit despite using process.nextTick()

I am currently developing a module for creating "chainable" validation in Express.js: const validatePost = (req, res, next) => { validator.validate(req.body) .expect('name.first') .present('This parameter is required') ...

Express.js experiencing difficulty integrating with Share.js

When it comes to Server-Side code, var express = require('express'); //Web Framework var app = express(); var http = require('http').Server(app); //HTTP server module var connect = require('connect'), sharejs = require(&a ...

The handler provided to Boost::asio::async_read_until is never triggered

I am attempting to establish a connection between two computers on a local network. One is using a slightly modified version of the Boost Asio C++ TCP asynchronous server sample, while the other is running NodeJS. tcp_client.js : var net = require(' ...

Creating HTML inputs dynamically using jQuery in an ASP.NET application

I have written this JavaScript code to dynamically generate and add HTML elements within my asp.net webform: var i = 0; function addFields() { i++; var quantity = '<td class="auto-style2"><input type="text" size="3" name= ...

TypeScript: restrict access to field to exclusive classes only

Here's an interesting dilemma I am facing. In my project, I adhere to the MVVM architecture pattern where I have separate Views for display logic and ViewModels for functional logic. The ViewModels contain methods and fields that can be accessed by ot ...

What are the steps to correctly implement async await in a standard sequence?

When I press the button onPress={() => Login()} First, I need to obtain a token by using the signInWithKakao function. Secondly, right after acquiring the token, if it is available, I want to dispatch the profile using the kakaoprofile function. Howev ...

Unable to instantiate a Vue reference with a potential null type

When working in Vue v3, I encountered a situation where I needed to create a ref with a type that could possibly be null. This specific scenario in my app involves data that starts off as null and then gets populated after loading completes. Just to illus ...

Node.js: Verifying the user's previous login status using Passport

My current express router for users handles user logins using a token system: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var Veri ...

I'm having trouble locating the source of the popstate loop that is generating numerous history entries

I am currently working on a project to create a dynamic webpage where the content of the main div gets replaced when certain navigation links are clicked. I have successfully implemented the pushstate function to update the div content and change the URL a ...

The MVC execution sequence: Controller initialization happening after Ajax call

I'm struggling to understand the execution order in MVC architecture. In my code, I am overriding initialization in the following way: public class HomeController: Controller { protected override void Initialize(RequestContext requestContext) ...

Building projects using Vue.js and Django: An ultimate development environment

Embarking on a new learning project, I've decided to experiment with Vue.js and Django (using DRF). My approach involves using the vue loader within the webpack-simple template. However, I'm currently facing an issue regarding the synchronizatio ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

Explore additional sub-categories by clicking on them with the help of jQuery or alternate techniques

I am currently working on a Magento store that has Categories with an overwhelming amount of sub-categories, taking up almost half of the page. I want to enhance user experience by implementing a feature that displays a "Load more" button when there are mo ...

During operation, invoking the next-auth function Signout() in production will direct the user to "localhost:3000" regardless of whether a callbackUrl is provided

After successfully deploying my Next.js app to AWS Amplify and setting up my environment variables correctly (including APP_URL and NEXTAUTH_URL, which are the same), I encountered an issue when attempting to sign out using credentials from MongoDB Atlas. ...

Google Maps JavaScript API failing to load due to a 403 error after the tab has been open for an extended period

Our website utilizes Angular and includes tabs with Google Maps that load lazily when needed. Everything works fine when the page is first opened, but after spending some time on a tab without a map, switching to a new tab with a map results in the map not ...

What is the best way to open a new window, such as a music player, and integrate it into a Shopify environment

Currently, within my Shopify store, I am using the following code: <script language="javascript" type="text/javascript"> function popupwindow(url, winName, w, h) { var left = (screen.width/2)-(w/2); var top = (screen.height/2)-(h/2); return wi ...

Define JSON as writeable: 'Error not caught'

I'm facing an issue with a read/write error in my JavaScript code because the JSON file seems to be set as read-only ('Uncaught TypeError: Cannot assign to read only property'). How can I change it to writable? Should I make changes in the J ...

Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected. How can I fix the issue with the click event not working? The gets functi ...