简体   繁体   中英

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. 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 . But, movie.time_session is an array of sessions and doesn't have a time property. You probably need to compare to the time of each element of the time_session array.

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.

In your case you can make a computed property filteredMovies that returns the filtered movies and use that in your template instead:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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