Im looking for right way to write this, I have an array of students and every student has an attribute isSelected which is set to true or false, when the button is clicked, student is selected and this is the method: (I want others students attributes to be set to false)
selectStudent(id) {
this.students[id].isSelected = true
this.selectedStudent = this.students[id]
let studentsFalse = this.students.filter(studentId => studentId != this.students[id])
for (let i= 0; i < studentsFalse.length; i++) {
studentsFalse[i].isSelected = false
}
},
You could just loop through the array and set the values to true or false depending on whether the item is at the correct index.
selectStudent(id) {
this.selectedStudent = this.students[id]
for (let i= 0; i < this.students.length; i++) {
this.students[i].isSelected = i === id;
}
},
With generic for you may do this, all students will have their property modified, just check if the student's key matches the id parameter.
selectStudent(id) {
this.selectedStudent = this.students[id];
for (let key=0; key<this.students.length; key++) {
this.students[key].isSelected = key === id;
}
}
To test here:
const object = {
students: [
{
name: "Fernanda",
isSelected: false
},
{
name: "Paula",
isSelected: false
},
{
name: "Gabriel",
isSelected: false
}
],
selectedStudent: null,
selectStudent(id) {
this.selectedStudent = this.students[id];
for (let key=0; key<this.students.length; key++) {
this.students[key].isSelected = key === id;
}
}
}
object.selectStudent(1);
console.log(`Selected student: ${object.selectedStudent.name}`);
object.selectStudent(2);
console.log(`New selected student: ${object.selectedStudent.name}`);
console.log(object.students);
Working Demo :
const app = new Vue({
el: '#app',
data: {
students: [{
id: 1,
name: 'Student 1',
isSelected: false
}, {
id: 2,
name: 'Student 2',
isSelected: false
}],
studentSelected: false
},
methods: {
selectStudent(event) {
if (event.target.checked) {
this.students.forEach((student) => {
student.isSelected = parseInt(event.target.value) === parseInt(student.id)
})
}
console.log('updated students list : ', this.students)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="student in students" :key="student.id">
<input type="checkbox" :value="student.id" v-model="student.isSelected" id="student.id" @click="selectStudent">
{{student.name}}
</li>
</ul>
</div>