[Vuejs]-Set attribute of the object in array to true but others to false

0👍

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;
        }
    },

0👍

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);

0👍

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>

Leave a comment