[Vuejs]-Vuejs – check if two data of different lists are same to display in the template

0👍

Basically you need to create a computed property where you gather your data which is ready to be rendered. Docs about computed properties: https://v2.vuejs.org/v2/guide/computed.html

Computed property is the way to go if you need to extract a piece of data, format it somehow, etc.

Also you need two v-for loops: one to loop through blocks and a nested one to loop through time ids.

Here’s an example:

new Vue({
  el: '#app',
  data: {
    myArr: [
      {
        "id": 7,
        "day": "14 April 2017",
        "time_list": [
          {
            "id": 25,
            "time": "11:00 AM",
          },
          {
            "id": 28,
            "time": "08:00 PM",
          }
        ]
      },
      {
        "id": 7,
        "day": "13 April 2017",
        "time_list": [
          {
            "id": 33,
            "time": "11:00 AM",
          },
          {
            "id": 22,
            "time": "02:00 PM",
          },
        ]
      },
    ], 
    default_time_data: ["11:00 AM", "02:00 PM", "05:00 PM", "08:00 PM"]
  },
  computed: {
    dataToRender: function() {
      return (this.myArr && this.myArr.length > 0) // if data is already fetched
        ? this.myArr.map(e => Object.assign({ day: e.day }, 
          { 
            timeList: this.default_time_data
              // if time in default array - return id, otherwise 'No data'
              .map(dt => (e.time_list.map(({time}) => time).includes(dt)) ? e.time_list.find(tl => tl.time === dt).id : 'No data')
          }))
        : []; // if data hasn't arrived - return empty array
    }
  }
});
<script src="https://unpkg.com/vue@2.3.3/dist/vue.min.js"></script>

<div id="app">
   <ul v-if="dataToRender.length > 0"> <!-- check if data exists -->
     <li v-for="item of dataToRender">
       <p>{{ item.day }}</p>
       <ul>
         <li v-for="time of item.timeList">{{ time }}</li>
       </ul>
     </li>
   </ul>
</div>

Leave a comment