Having trouble iterating through an array of objects in Vue?

Having trouble looping through an array of objects in Vue3

<template>
  <div
    class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md"
  >
    <button @click="getData">Get data</button>
    <ul v-for="question in questions" :key="question.answer">
      <li>{{ question.answer }}</li>
    </ul>
  </div>
</template> 

The data structure is as follows:

questions: [
        { "answer": "Paris", "correct": true },
        { "answer": "Tokio", "correct": false },
        { "correct": false, "answer": "Dubai" },
        { "answer": "London", "correct": false }
      ]

I have correctly fetched the data from the database. However, when I use:

<ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answers }}</li>

I get an array of object that looks like this:

[ { "answer": "Paris", "correct": true }, { "answer": "Tokio", "correct": false }, { "answer": "Dubai", "correct": false }, { "answer": "London", "correct": false } ]

But if I want to display only the city names and change the code to:

<ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answer }}</li>

or even

   <ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answers.answer }}</li>

It doesn't work. Where am I making a mistake? I have two questions stored as documents in Firestore. Perhaps I need to use v-for twice...

<ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answer }}</li>

or even

   <ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answers.answer }}</li>

Answer №1

const questionsList = [
  [
        { "option": "Paris", "valid": true },
        { "option": "Tokio", "valid": false },
        { "valid": false, "option": "Dubai" },
        { "option": "London", "valid": false }
      ],
  [
        { "option": "city 1", "valid": true },
        { "option": "city 2", "valid": false },
        { "valid": false, "option": "city 3" },
        { "option": "city 4", "valid": false }
      ]
];

Once the author received the actual API response, fixing it was simple - just utilize Array::flat():

v-for="question in questions.flat()"

LINK

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

Is it possible to update only the inner text of all elements throughout a webpage?

Scenario After coming across a thought-provoking XKCD comic, I decided to craft a script that would bring the comic's concept to life: javascript:var a=document.getElementsByTagName('body')[0].innerHTML;a=a.replace(/Program(\w\w+ ...

The use of multiple Where clauses in a Firestore Firebase query is not functioning as expected when implemented in JavaScript code

https://i.stack.imgur.com/DdUGj.png db.collection('User_Info').where("User_Name", "==", "Sam").where("PASSWORD", "==", "c2FtMTIzQA==").get().then(snapshot => { if(snapshot.docs.length > 0 ){ debugger; alert("Login Successful."); ...

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

The AJAX function fails to trigger the MVC controller method

I'm attempting to enable inline editing by cell, rather than by row, when double-clicking. Although the initial setup is working, it's not updating the record as expected - the "SaveCustomer" call to the controller isn't triggered. Can anyon ...

What is the proper method for updating state in vuex within vue.js 2?

Here is the structure of my Vue component : <template> <div> <div class="row"> <div class="col-sm-3"> <div class="form-group"> <label for="status" class="sr-only" ...

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...

What is the best way to incorporate intervals and polling in Angular 2 for seamless integration with Protractor?

I have an angular2 application that I am looking to test using protractor. Within this application, there is a page featuring a graph that updates at regular intervals with data generated on its own. It appears that one aspect of protractor is the abilit ...

Having trouble fetching API objects successfully

I've recently ventured into the use of the @nuxtjs/strapi package in combination with Strapi 4 and Nuxt 3. Unfortunately, I have found that this module is not well-documented, leaving me unsure about how to properly extract information from my API. He ...

The process of locating a textarea by its id becomes obsolete when integrating CKEDITOR

The data table has editable cells, where clicking on a cell will trigger a bootstrap modal to display with a textarea containing the text retrieved from the database. Snippet of the table structure: <table class="table table-striped table-hover" id="t ...

What are some ways to conceal the API connection within a button?

I have a code that allows me to perform a certain API call with a link. Here is an example: <a class="btn btn-default" href="https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey='.$user.'&Password='.$pass.'&Domain=&ap ...

Tips for organizing an array of objects that contain null properties

Here is an array that I need help with: "data": { "risks": [ { "id": "22", "name": true, "surname": 0.5, "age": 0.75, "heigth" ...

Encountering a TypeError in semantic-ui-react Menu: instance.render function not found

As a React novice, I have been working on a project that involves React for some time. However, I had not yet delved into dealing with packages and dependencies. It seems like my current issue is related to this. The problem emerged in a project where I w ...

Using Backbone for the front end and Node.js for the backend, this website combines powerful technologies

Currently, I am in the process of developing a new website that will function as a single-page application featuring dialog/modal windows. My intention is to utilize Backbone for the frontend and establish communication with the backend through ajax/webs ...

Troubleshooting ng-repeat in AngularJS: Multi checkbox filter malfunction

My AngularJS app has multiple age range filters implemented, but one of them is not functioning correctly and I can't figure out why. You can view a functional example here. The various filters are defined as follows: .filter('five', func ...

Is it possible to use a Backbone Model for an unconventional HTTP POST request that isn't

After going through the documentation at and , I tried to make an HTTP POST request to fetch some JSON data for my model. However, due to the services not being RESTful, I ended up using a POST request instead of a GET request. The code snippet I have co ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...

Troubleshooting issue with AngularJS ng-repeat not functioning properly when using Object key value filter with ng-model

Is there a way to have an object with an ID as a key value pair? For example: friends = { 1:{name:'John', age:25, gender:'boy'}, 2:{name:'Jessie', age:30, gender:'girl'}, 3:{name:'Johanna', ag ...

Upcoming construction: Issue encountered - The Babel loader in Next.js is unable to process .mjs or .cjs configuration files

Within my package.json file, I have set "type": "module" and "next": "^12.2.5". In my tsconfig.json: { "compilerOptions": { "target": "ES2022", "module": "esnext ...

Check that a string field includes specific characters and digits using JavaScript

I'm in the process of developing a React application that includes an input field requiring a specific format: The first four characters (char 1,2,3, and 4) must be "VTF_" followed by numbers for the remaining part of the string. For example, VTF_12 ...