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
}
},
CodePudding user response:
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;
}
},
CodePudding user response:
Just a for...in to 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 (const key in this.students) {
this.students[key].isSelected = key === id;
}
}
To test here:
const object = {
students: {
"1": {
name: "Fernanda",
isSelected: false
},
"2": {
name: "Paula",
isSelected: false
},
"3": {
name: "Gabriel",
isSelected: false
}
},
selectedStudent: null,
selectStudent(id) {
this.selectedStudent = this.students[id];
for (const key in this.students) {
this.students[key].isSelected = key === id;
}
}
}
object.selectStudent("2");
console.log(`Selected student: ${object.selectedStudent.name}`);
object.selectStudent("3");
console.log(`New selected student: ${object.selectedStudent.name}`);
console.log(object.students);