Home > database >  select some objects from object list through for loop based on a condition
select some objects from object list through for loop based on a condition

Time:02-28

say I have list of objects retrieved from database and I'm iterating them through foreach loop in script bloc

export default {
  props: {
    guests: {
      type: Object,
      default: null,
    },
...
},
  computed: {
myGuests() {
      this.guests.forEach(guest => {
  // the if guest.age > than 18 condition should be here 
        const myGuests = JSON.parse(JSON.stringify(guest));
        // body of my method
      });
      return ...;
    },
},

I want to make a condition on it so if the age is greater than 18 I store them on another object, then when I call the method from template bloc the directive v-for should go through those elements (i.e guests whose age is greater than 18 (instead of going through all of guests with their different ages))

v-for="(guest, g) in myGuests" //call for the new created object whose age property is > 18
:key="g"
...

CodePudding user response:

You can use filter in computed property:

Vue.component('Child', {
  template: `
    <div>
      <div v-for="(guest, g) in myGuests" :key="g">
        {{ guest.name }} - {{ guest.age }}
      </div>
    </div>
  `,
  props: {
    guests: {
      type: Array,
      default: null,
    },
  },
  computed: {
    myGuests() {
      return this.guests.filter(g => g.age > 18)
    }
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      guests: [{'name': 'aa', 'age': 15}, {'name': 'bb', 'age': 21}, {'name': 'cc', 'age': 18}, {'name': 'dd', 'age': 19}, {'name': 'ee', 'age': 20}, {'name': 'ff', 'age': 24}]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <child :guests="guests"> </child>
</div>

  • Related