/I have the following JSON data. I need to list students doing a particular subject. How can this be done using v-for in VUEJS?/
students_subjects:
[
{
student_id:1,
student_name:"Moses",
reg_no:"ABC/2019",
subjects:[
{
subject_id:1
subject_name:"English"
},
{
subject_id:2
subject_name:"Maths"
}
]
},
{
student_id:2,
student_name:"James",
reg_no:"ABD/2019",
subjects:[
{
subject_id:1
subject_name:"English"
},
{
subject_id:2
subject_name:"Maths"
}
]
}
]
// My structure of html code is as shown below
<div id="app">
<ul>
<li v-for="item in students">
<div class="row " style="background-color: #f4fbee;">
<div class="col-md-2">{{item.reg_no}}</div>
</div>
<div class="row" v-for="subjects in item.subjects">{{subjects.subject_name}}
</div>
</li>
</ul>
<pre>{{students}}</pre>
<p>{{getStudentsBySubjectId}}</p>
</div>
var appVM=new Vue({
el:"#app",
data:function(){
return {
student_id: '',
reg_no:'',
student_name:'',
students:Array(),
subjects:{},
}
},
created:function (){
this.getAllStudents();
},
methods:{
getAllStudents:function(){
var self=this;
axios.get("/Students/list").then(function (response) {
this.students = response.data;
}.bind(this)).catch(function (error) {
console.log('Error while fetching student data: ' + error)
})
},
getStudentsBySubjectId:function (students, subjectId) {
return students.filter(function(student) {
return student.subjects.some(function(subject) {
return subject.subject_id === subjectId;
})
})
}
},
})
</script>
// How do we get to display the filtered students. //The code above shows the data returned on on calling the array on the view