Search code examples
vue.jsv-for

nested v-for vuejs in a table


I have two set of data.

List of Time Durations

 timeDurations: [
   { 'duration': '02:30 AM - 03:00 AM' },
   { 'duration': '03:00 AM - 03:30 AM' },
   { 'duration': '03:30 AM - 04:00 AM' },
   { 'duration': '04:00 AM - 04:30 AM' },
   { 'duration': '04:30 AM - 05:00 AM' },
   { 'duration': '05:00 AM - 05:30 AM' },
   { 'duration': '05:30 AM - 06:00 AM' }
 ];

List of Bus assigned to that specific duration

 assignedBus: [
   { 'duration': '03:00 AM - 03:30 AM', 'bus': 'Bus1' },
   { 'duration': '04:00 AM - 04:30 AM', 'bus': 'Bus2' },
   { 'duration': '05:00 AM - 05:30 AM', 'bus': 'Bus3' }
 ];

I am using table to display that List of Time Durations using vue js

  <table class="table table-striped table-bordered table-hovered">
    <thead>
      <tr>
        <th>Time Duration</th>
        <th>Bus</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="time in timeDurations">
        <td>{{time.duration}}</td>
        <td><button class="btn btn-primary">Assign Bus</button></td>
      </tr>
    </tbody>
  </table>

But actually, I want to display the time durations and corresponding button based on assignedBus data

the values in the table must be like this

|     Time Durations     |     Action    |
|   02:30 AM - 03:00 AM  |   Assign Bus  |
|   03:00 AM - 03:30 AM  |    View Bus   |
|   03:30 AM - 04:00 AM  |   Assign Bus  |
|   04:00 AM - 04:30 AM  |    View Bus   |
|   04:30 AM - 05:00 AM  |   Assign Bus  |
|   05:00 AM - 05:30 AM  |    View Bus   |
|   05:30 AM - 06:00 AM  |   Assign Bus  |

So, if timeDurations has matching data in assignedBus the button must be View Bus else Assign Bus

here's my fiddle -> https://jsfiddle.net/943bx5px/31/

please help. Thanks


Solution

  • The problem is caused by the for loop in the for loop. Check my solution:

    hasAssignedBus(duration) {
      for (var i = 0; i < this.assignedBus.length; i++) {
          if(this.assignedBus[i].duration == duration) {
            return true;
          }
      }
      return false;
    }
    

    cheers