This is a complex v-for loop nested inside another v-for. It displays a list of questions along with the corresponding answers for each question. The key for the question will be used as the key for grouped_answers.
The structure of the v-for loop is shown below:
<div v-for="question in questions.questions">
{{question.question}}
<div v-for="a in grouped_answers[0].answers">
{{a.answer}}
</div>
</div>
Currently, it's throwing an error:
Cannot read property 'answers' of undefined.
An example of the grouped_answers object is provided below:
[
{
"question_id": 1,
"answers": [
{
"id": 1,
"answer": "Cat"
},
{
"id": 2,
"answer": "Dog"
}
]
},
{
"question_id": 2,
"answers": [
{
"id": 3,
"answer": "Fish"
},
{
"id": 4,
"answer": "Ant"
}
]
}
]
For the complete template code, please refer to the snippet below:
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<!-- Existing HTML code -->
<div v-for="question in questions.questions">
{{question.question}}
<div v-for="a in grouped_answers[0].answers" v-if="grouped_answers">
{{a.answer}}
</div>
</div>
<br>
<!-- Additional form elements -->
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
mounted() {
console.log('Component ready.');
this.appliances = JSON.parse(this.a);
this.brands = JSON.parse(this.b);
},
props: ['a','b'],
data: function() {
return {
appliances: '',
appliance: '',
brands: '',
brand: '',
age: '',
first_name: '',
last_name: '',
phone_number: '',
email: '',
questions: '',
answers: '',
grouped_answers:'',
}
},
methods: {
getQuestions: function (){
var self = this;
axios.get('/get_questions/' + this.appliance)
.then(function(response) {
self.questions = response.data;
self.getAnswers();
})
.catch(function(error) {
console.log(error);
});
},
getAnswers: function (){
var self = this;
axios.get('/get_answers/' + this.appliance)
.then(function(response) {
self.answers = response.data;
self.putAnswers();
})
.catch(function(error) {
console.log(error);
});
},
putAnswers: function (){
var result = {};
for (var i = 0; i < this.answers.answers.length; i++) {
var question_id = this.answers.answers[i].question_id;
if(!result[question_id]) {
result[question_id] = {question_id: question_id, answers: []};
}
result[question_id].answers.push({
id: this.answers.answers[i].id,
answer: this.answers.answers[i].answer})
}
result = Object.keys(result).map(function (key) { return result[key]; });
this.grouped_answers = result;
},
},
}
</script>
UPDATE AFTER RECOMMENDATION
<div v-for="question in questions.questions">
{{question.question}}
<div v-for="a in grouped_answers[0].answers" v-if="grouped_answers">
{{a.answer}}
</div>
</div>