简体   繁体   English

如何在VueJS中按对象属性过滤对象数组

[英]How to filter array of objects by object property in VueJS

I want to print out the movies that have time sessions that start after the hour 20 or the same day. 我想打印出具有在20小时或同一天之后开始的时间段的电影。 Either way, I can't get it to work. 无论哪种方式,我都无法正常工作。

Component data structure: 组件数据结构:

day:"2017-06-08T18:34:27.211Z"
movies:Array[8]
0:Object
   Description:"orphan the becomes a famous magician "
   id:1
   movieName:"Harry Potter "
   time_session:Array[3]
     0:Object
       id:1
       pivot:Object
       time:"2017-06-14 00:00:00"
     1:Object
     2:Object
1:Object
2:Object
3:Object
4:Object

Template: 模板:

<template>
  <div> 
    <li v-for="movie in filteration(movies)">{{movie.movieName}}</li>
  </div>
</template>

How can I filter the movies so that the movies displayed depend on the time sessions in that same Object? 如何过滤影片,以便显示的影片取决于同一对象中的时间段?

Here's what I've tried: 这是我尝试过的:

<script>
  export default{
    data() {
      return {
        movies:[],
        day:moment()
      }
    },  
    mounted(){
      axios.get("/fa")
        .then(response  => this.movies = response.data);
    },
    methods:{
      filteration(movie){
        return movie.filter(this.time);
      },
      time(movie){
        return moment(movie.time_session.time).hour() > 20;
        // return moment(movie.time_session.time).isSame(this.day,'day');
      }    
    }
  }     
</script>

The most likely reason you're having issues is that you are passing movie.time_session.time to moment . 您遇到问题的最可能原因是您将movie.time_session.time传递给了moment But, movie.time_session is an array of sessions and doesn't have a time property. 但是, movie.time_session是一个会话数组,没有time属性。 You probably need to compare to the time of each element of the time_session array. 您可能需要比较time_session数组中每个元素的时间。

Generally, the best way to display an array of filtered data in Vue is to make a computed property that filters the data and returns it. 通常,在Vue中显示过滤数据数组的最佳方法是创建一个计算属性,该属性可以过滤数据并返回数据。

In your case you can make a computed property filteredMovies that returns the filtered movies and use that in your template instead: 在您的情况下,您可以使计算所得的属性filteredMovies返回已过滤的电影,并在模板中使用它:

computed: {
  filteredMovies() {
    return this.movies.filter((movie) => { 
      return movie.time_session.reduce((acc, session) => {
        return acc || (moment(session.time).hour() > 20);
      }, false);
    });
  }
}

Then, in your template, reference filteredMovies like so: 然后,在您的模板中,按如下所示引用filteredMovies

<li v-for="movie in filteredMovies">{{movie.movieName}}</li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM