Vuejs v-for nested loops

After spending countless hours researching, I am determined to solve this problem. My objective is to create a questionnaire similar to a Google Form, with question groups, questions, and answers.

The structure of my data looks like this:

question_group: [ { str : "Addition",
                    questions: [{ str: "1+1",
                                 type: "multiple_choice",
                                 answer_choices: [1, 2, 3, 4, 5]
                                 },
                               { str: "2+2",
                                 type: "multiple_choice",
                                 answer_choices: [1, 2, 3, 4, 5]
                               }
                              ] 
                   },
                   { str : "Subtraction",
                     questions: [{ str: "2-1",
                                  type: "multiple_choice",
                                  answer_choices: [1, 2, 3, 4, 5]
                                }
                               ] 
                   }
                 ] 

Desired output :

Addition
1. 1+1
a. 1
b. 2
c. 3
d. 4
e. 5

2. 2+2
a. 1
b. 2
c. 3
d. 4
e. 5

Subtraction
1. 2-1
a. 1
b. 2
c. 3
d. 4
e. 5

I am considering using the following loop for display:

<div v-for="(group, i) in question_group" :key="'group' + i">
     <div class="col-12">
        <label>{{ group.str }}</label>
     </div>
     <div v-for="(question, y) in questions" :key="'question' + y">
          <label>{{ index }} {{ question.str }}</label>
          <div v-for="(answer, z) in answer_choices" :key="'answer' + z">
               <label>{{ alphabet[index] }}. {{ answer[z] }}</label>
          </div>
     </div>
</div>

Answer №1

If you are looping through an array using v-for, the second argument represents the index of the current entry.

Therefore, your HTML code should look something like this:

new Vue({
  el: "#app",
  data: {
    alphabet: ['a', 'b', 'c', 'd', 'e'],
    question_group: [{
        str: "Addition",
        questions: [{
            str: "1+1",
            type: "multiple_choice",
            answer_choices: [1, 2, 3, 4, 5]
          },
          {
            str: "2+2",
            type: "multiple_choice",
            answer_choices: [1, 2, 3, 4, 5]
          }
        ]
      },
      {
        str: "Subtraction",
        questions: [{
          str: "2-1",
          type: "multiple_choice",
          answer_choices: [1, 2, 3, 4, 5]
        }]
      }
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(group, i) in question_group" :key="'group' + i">
    <div class="col-12">
      <label>{{ group.str }}</label>
    </div>
    <div v-for="(question,y) in group.questions" :key="'question' + y">
      <label>{{ y+1 }}. {{ question.str }}</label>
      <div v-for="(answer,z)  in question.answer_choices" :key="'answer' + z">
        <label> {{ alphabet[z] }}.  {{answer}}</label>
      </div>
    </div>
  </div>
</div>

For more information, please refer to the official documentation.

Answer №2

Is this what you're talking about?

<div v-for="(group, i) in question_group" :key="'group' + i">
     <div class="col-12">
        <label>{{ group.str }}</label>
     </div>
     <div v-for="(question, y) in group.questions" :key="'question' + y">
          <label>{{ index }} {{ question.str }}</label>
          <div v-for="(answer, z) in question.answer_choice" :key="'answer' + z">
               <label>{{ alphabet[index] }}. {{ answer[z] }}</label>
          </div>
     </div>
</div>

Answer №3

Here is a solution to address the issue at hand

<div id="app">
  <div v-for="(group, i) in question_group" :key="'group' + i">
    <div class="col-12">
      <label>{{ group.str }}</label>
    </div>
    <div v-for="(question, question_index) in group.questions" :key="'question' + question_index">
      <label>{{ question_index + 1 }} {{ question.str }}</label>
      <ol type='a'>
      <li v-for="(answer, answer_index) in question.answer_choice" :key="'answer' + answer_index">{{ answer }}</li>
      </ol>
    </div>
  </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

Tips for testing components with React JS using jest and enzyme

Attempting to perform a unit test on the code snippet below: handleChange = (e) => { let localState = Object.assign({}, this.state) localState[e.target.name] = e.target.value this.setState(localState) this.props.addMetaInformation(localState) } } I&a ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

What is the method for dynamically toggling an HTML property without a value in Vue.js?

My desire is for it to be displayed like this: // normal <div></div> // when necessary, add a `data-locked` attribute without a value to it <div data-locked></div> I attempted <div :data-locked='conditionBoolean'>&l ...

Utilizing jQuery/Javascript to replicate the data from a table while excluding the header and then pasting it to the

I am attempting to replicate the data from a table while disregarding the header/title row and copying it to the clipboard in the exact same way as manual selection and copy. I came across a post on how to choose Select a complete table with Javascript (t ...

Structuring Server Side Code with Node.js and Express

I am faced with the task of restructuring my server and its components. My goal is to streamline the process by segregating different functionalities. app.post("/login", function(request, response) { }); app.post("/register", function(request, response) ...

What is the best way to ensure that empty strings are not included in the length of my array?

I have encountered an issue with a JSON file that I fetch. The array syllables is capable of holding up to strings max. However, when I exclude 2 words, I end up with 2 words and 2 empty strings. Nevertheless, my front-end still expects 4 "strings". So, it ...

Using a JavaScript if statement to check the height of a specific HTML element

I have been struggling to figure out how to insert an if-else statement in JavaScript that references data about an HTML element. My objective is to create an "onclick" function that enlarges an image with a 200ms delay and another function that returns th ...

Guide to setting up CKeditor

I am struggling with the installation of CKEditor. After downloading the editor from the website, I inserted the code below between the head tags of my webpage: <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <script typ ...

Using a single function to generate multiple instances of a table in JavaScript

My journey to learning javascript led me to create a simple game called circle of crosses. Below is the code I used: (JS) // JavaScript code here (HTML) <!DOCTYPE html> <html> // HTML code here </html> I came across an issue whil ...

Tips for turning off the auto save password option on browsers for user registration forms

Is there a way to prevent browsers from saving passwords on the add users form? I've tried using autocomplete="off" but it doesn't seem to work for saved passwords. I've searched extensively for a solution but haven't found the right on ...

The hovering effect on the image link is causing the surrounding div to stretch too far

Whenever I hover over specific points below an image link wrapped in a div, it triggers the hovering effect for the CSS-created image link. Despite trying various solutions like overflow:hidden and display:inline-block, nothing seems to resolve this issue. ...

The express app is configured to send a 301 status code when Supertest is used, and it is

Hello, I am currently utilizing supertest to test the functionality of my Node.js express server application. My goal is to accomplish the following: let request = require('supertest'); let app = require('./server.js'); request(app). ...

Node.js project is set up globally on personal system

Introduction I'm diving into the world of Node.js and eager to learn. NPM has been a game changer for me as I can easily install packages globally and utilize them as standalone applications accessible from anywhere on my system. To my surprise, thi ...

Encountering a JavaScript error in the backend of Joomla 3.2

I am facing an issue with buttons on my Joomla 3.2.3 sites in the backend. The save, edit (material, module, menu...) buttons are not working properly. These sites were deployed using Akeeba Kickstart. Interestingly, everything worked fine on the developme ...

In Javascript, create a variable that dynamically updates for every child element

While this might appear to be a simple question, it has been troubling me for some time now. Let me elaborate on what I am trying to accomplish. I have a collection of images in a gallery, and my goal is to center each image vertically within its contain ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

Using mysql_real_escape_string for an array: Best practices for escaping array data in MySQL

I need to save a collection of data submitted through $_POST (as an array) using the INSERT method: foreach($_POST['data'] as $single) { $set[]="('static', '$single')"; } $sets=implode(", ", $set); mysql_query("INSERT INTO ta ...

jQuery mobile menu: Scroll to content after closing the menu

I am currently working on a project where I am using mmenu for the first time. It's functioning as expected, but there is one particular issue that I would really like to have resolved. Here is the URL: What I am hoping to achieve is that when a men ...

transmit JSON formatted form data to an AngularJS platform

I have a webpage built on AngularJS with a login feature. I want to iframe this webpage onto my own page and automatically log in my users. Upon inspecting the AngularJS site, I noticed that the login procedure expects a json object. I have tried multipl ...