Ash Bryant
Ash Bryant

Reputation: 13

Return the first 3 items that have a given property in vue.js

I'm learning vue.js by doing and I'm trying to make a store locator.

I have markers (stores) that have some properties such name and if it is a 'featured' location (true/false)...

so I do this

`<template v-for="featured in featuredLocations"> 
     <div v-if="featured.featured_location == true">
          <Featured 
             :name="featured.name"
             :image="featured.image"
             :facebook="featured.facebook_url"
             :twitter="featured.twitter_url"
             :featuredLocation="featured.featured_location"
          />
     </div>
</template>`

and ...

`computed: {
     featuredLocations: function(){
          return _.orderBy(this.markers, 'name') // order A-Z
     }
}`

This I know is looping through the markers and only displaying them if they are featured ones, however, what I really want to do is a loop through the featured ones and only show the first 3. I'm not sure how to do that, but I'm sure I'm missing something simple.

Upvotes: 0

Views: 59

Answers (1)

Sovalina
Sovalina

Reputation: 5609

You can use the lodash take function:

computed: {
  featuredLocations: function(){
    let featured = _.filter(_.orderBy(this.markers, 'name'), marker => marker.featured_location)
    return _.take(featured, 3)
  }
}

Note: with a filter function on your computed property, you don't need the v-if="featured.featured_location == true" condition anymore

Upvotes: 1

Related Questions