如何基于两个数组的比较进行过滤?

时间:2019-10-07 19:05:53

标签: vue.js

所以,我有两个数组。其中包含一些约会,所有约会都说明了他们预定的日期。在另一个数组中,我有所有工作日的名称。我只想打印有约会的工作日。

<b-col class="h-100">
    <b-row v-for="day in week" class="schemaLine">
        <div>{{day}}</div>
        <b-row v-for="appointment in appointments" class="">

            <div v-if="appointment.day === day && companies.includes(appointment.company)">

                <b-button class="appointmentBlock w-100 m-2">
                    <div class="appointmentTitle">
                        {{appointment.name}}
                    </div>
                    <div class="appointmentTime">
                        {{appointment.time}}
                    </div>
                </b-button>
            </div>
        </b-row>
    </b-row>
</b-col>

2 个答案:

答案 0 :(得分:0)

仅打印您至少有一个约会的日期的最简单方法是预处理约会。这样做还有一个好处,就是不需要您每周都要处理所有约会。

首先,我们创建一个计算属性appointmentsPerDay,该属性将一天映射到一组约会。然后,我们创建另一个计算属性,该属性使用该对象的键并对键进行排序,以便您可以对它们进行循环:

computed: {
  appointmentsPerDay () {
    // We assume that you get the appointments variable somehow
    const appointmentsPerDay = {};

    for (const appointment of this.appointments) {
      const { day } = appointment;

      // We initialise an array if no such array exists
      if (!appointmentsPerDay[day]) {
        appointmentsPerDay[day] = [];
      }

      // Now that it is guaranteed that we have an array, add our appointment to it
      appointmentsPerDay[day].push(appointment);
    }

    return appointmentsPerDay;
  },

  visibleDays() {
    const days = Object.keys(this.appointmentsPerDAy);
    days.sort();
    return days;
  }
}

现在我们如何使用这些?

<b-col class="h-100">
    <b-row v-for="day in visibleDays" class="schemaLine">
        <div>{{day}}</div>
        <b-row v-for="appointment in appointmentsPerDay[day]" class="">

            <div v-if="companies.includes(appointment.company)">

                <b-button class="appointmentBlock w-100 m-2">
                    <div class="appointmentTitle">
                        {{appointment.name}}
                    </div>
                    <div class="appointmentTime">
                        {{appointment.time}}
                    </div>
                </b-button>
            </div>
        </b-row>
    </b-row>
</b-col>

如您所见,我们只需要交换一些变量。您仍然看到我们必须使用v-if来筛选公司。显然,我们也可以对其进行预处理,以完全消除v-if,然后循环遍历我们实际想要显示的数据。我会将其留给您练习。

答案 1 :(得分:0)

我相信week是您的weekdays数组,那么应该是这样的:

<b-row v-for="day in week" class="schemaLine" v-if="appointments.find(app => app.day === day)">
相关问题