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

Testing Angular: Inability to achieve full code coverage for Ternary branch in unit testing

Currently, I am attempting to test a ternary branch that utilizes the window.location property. @Injectable() export class ABCService { private hostUrl = (window.location.host.indexOf('localhost') > -1) ? 'example.com' : window.lo ...

When using res.json(), the data is returned as res.data. However, trying to access the _id property within it will result

I'm facing a challenge in comprehending why when I make a res.json call in my application, it successfully sends data (an order object). However, when I attempt to access and assign a specific piece of that data (res.data._id) into a variable, it retu ...

The computed property in Vue JS is providing an unexpected output

I need assistance with a task in Vue JS that I'm struggling with. I can't seem to figure out what's causing the issue in this code. The task involves creating a dynamic table with 5 columns, each with a background color of red, blue, yellow ...

Incorporating a stylish background image into an EJS template

I'm able to successfully display an image from my app.js file in the main ejs file, but when I try to set it as a background image, it doesn't show up. Any thoughts on what might be causing this issue? This is my app.js file: const express = re ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

Using the history.push() method from the Action Creator will update the URL without actually redirecting to a new page

I have a login page component that I've set up to redirect to another page after a successful login. However, even though the URL changes correctly, the page remains on the Login page. First, let me show you how I import the history module to be used ...

Is it possible to change the background color of the scrolling page?

Let's say I have 10 different sections, each with a unique background color assigned to them. As the user scrolls down from section 1 through 10, my goal is to dynamically change the body tag's background color based on which section is currentl ...

Incorporating a favicon into a Next.js React project

I'm currently working on integrating a favicon into a Next.js project that was generated using create-next-app. The favicon.png file is stored in the public folder, and I followed the instructions for serving static files outlined here. In my Layout ...

Having trouble with jQuery modal not adjusting its height properly

I am a jquery modal popup newcomer. I can open the modal when clicking on the hyperlink, but I'm having trouble with the height setting. Despite my attempts and searches online, I couldn't figure it out. When trying to post a question about the & ...

How can I modify the parent form element to only evaluate the expression at the text node, without affecting Angular interpolation?

Currently, I am in the process of developing an eCommerce platform and utilizing angular to construct a widget on product detail pages. Unfortunately, my control over the initial HTML rendered for the browser is quite limited. While most tasks related to m ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

What is the correct process for submitting an HTML form following the loading of asynchronous data?

I've been searching high and low, but I can't seem to find the solution to my problem. I've scoured search engines and Stack Overflow with no luck. My dilemma is this: How can I trigger the submission of an HTML form only after asynchronous ...

Showing a notification that is persistent and not dismissible

Hello everyone! I've been struggling with a problem on the RPS project for quite some time now. The issue arises when I try to display a message for a tie in the game, but I can't seem to find a solution to make it disappear when the round is not ...

a single function spread across two controllers[JavaScript]

My query pertains to a JavaScript program with 2 controllers. The issue I am facing is the need for one function in both controllers (data.duration). This function serves two purposes, once for features themselves and once for the summary. Currently, this ...

Lifting Formik's "dirty" value/state to the parent component: A step-by-step guide

Parent Component const Mother = () => { const [dusty, setDusty] = useState(false) return ( <ChildComponent setDusty={setDusty} /> ) } Child.js ... <Formik initialValues={initialValues} onSubmit={onSubmitHandler} validationSchema={sch ...

How to extract parameters from an http get request in Node.js

Trying to handle an HTTP request in this format: GET http://1.2.3.4/status?userID=1234 I am unable to extract the parameter userID from it. Despite using Express, I am facing difficulties. Even when attempting something like the following, it does not yi ...

Which slider was featured in the unity3d.com/5 website?

While browsing the internet, I came across the website and was intrigued by the slider effect featured in the "graphics" section. I am eager to figure out how to replicate that stunning visual effect. ...

Implement pagination for API calls within a React Component

I am trying to implement pagination for the results of an API call. The following code snippet shows how I am making the API call using Axios: apiCall() { const API = `http://www.omdbapi.com/`; axios.get(API, { params: { apikey: proces ...

Encountering an issue with resolving a local variable during the execution of a test with Protractor

I'm currently learning about async calls in protractor as a newbie to the tool. I am struggling to figure out how to handle a boolean variable that I set to true if any test case fails and the execution goes to the catch block for a promise. Below is ...

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...