[Vuejs]-How to use variable in the array name

0👍

You can use the variable name as index for your condensedAssignments variable, but, I think it can’t work because the index is a string and the variable day is a number.

You can do this:

<tr v-for="task_name in condensedAssignments[String(day).padStart(1, '0')]">
    <td>{{task_name}}</td>
</tr>

String(day) -> Cast variable to a string
.padStart(2, ‘0’) -> Add one zero at left because your index is ’05’ then two chars long

0👍

Actually, you have several problems here.

First, you should not use v-if and v-for on the same element. If you only want the first n elements, a solution could be to use the slice method : calendar.days_array.slice(0, 7)

The second anomaly is that your assignments variable isn’t an Array but an Object. You can search how to iterate through an object or check this Digital Ocean tutorial.

Also, you can call the second v-for statement on your variable instead of harcoding your taskname.

It may looks something like this :

<td v-for="(day, key, i) in calendar.days_array">
  <tr>{{ key }}</tr>
  <tr v-for="task_name in day">
    {{ task_name }}
  </tr>
</td>

0👍

Thank you to fdisotto for the quick answer. I tried again using a method in the meantime, and was reminded that I have another issue: My "day" field is sometimes null. I was able to get it working, though, with this method:

daysTasks: function(day){
   if (!day) {return []};
   if (String(day).length < 2) {
       day = '0'+day;
   }
   return this.assignments[day];
},

and this template:

<td v-for="(day, index) in calendar.days_array" :key='day' v-if="index < 7">
    <table>
       <tr>
          {{day}}
       </tr>
       <tr v-for="task_name in daysTasks(day)" :key='task_name'>
           <td>{{task_name}}
           </td>
       </tr>

Now, only the 5th of the month sees the first two tasks, and the 6th sees the last two.

Leave a comment