3

`I am looking to sort a quiz questions and answer that I am fetching from JSON file. in the vue template. I tried the v-for directive but I can't use the object key in the template. to make it more clear I will demonstrate what I did so far in the script section. looking to have something similar to this: 1 - first Question

  • a / first answer
  • b / send answer ....

this is the vue file

<template>
  <div class="lg:pl-64 flex flex-col">

    <div v-for="data in datas">
      <h1>{{ data.question }}</h1>
    </div>
    <div>
      // looking to add multiple choice answers in here
    </div>

  </div>
</template>
<script setup>
import myData from "../data/data.json"
const datas = myData
const answers = []


datas.forEach((element) => {
  // pushing all the answers from JSON file to the answers array
  answers.push(element.answers)
})

// looping throught the arrays of objects to bring the key and value
answers.forEach((answer) => {
  for (let i = 0; i < answer.length; i++) {
    for (const key in answer[i]) {
      console.log(`${key}: ${answer[i][key]}`)
    }
  }
})
</script>

and this is the data.JSON file

[
  {
    "id": 1,
    "question": "first Question",
    "answers": [{
        "a" : "first answer1",
        "b" : "second answer1",
        "c" : "third answer1",
        "z" : "fourth answer1"
    }],
    "correct": "a"
  }
,
    {
      "id": 2,
      "question": "second Question",
      "answers": [{
          "a" : "first answer2",
          "b" : "second answer2",
          "c" : "third answer2",
          "z" : "fourth answer2"
      }],
      "correct": "a"
    }
]
Oussama
  • 33
  • 4
  • Does this answer your question? [Vue Js - Loop via v-for X times (in a range)](https://stackoverflow.com/questions/44617484/vue-js-loop-via-v-for-x-times-in-a-range) – Anindya Dey Apr 09 '23 at 02:11

0 Answers0