2

I have an odd HTML setup that I need to loop through. I get my data in two parts from Firebase. There is a categories and a businesses set of data structured like so:

Businesses
    -UniqueFirebaseID
        cat: "food"

Categories
    -IniqueFirebaseID
        name: "food"

I then want to loop through my data like so (pardon the non-semantic markup):

<ul>
    <li v-for="cat in categories">
        <ul>
            <li v-for="business in filteredByCat">{{business.name}}</li>
        </ul>
    </li>
</ul>

I am trying to put together a computed property to filter. The one below represents what I'm trying to do but not sure how to do it. Any suggestions?

computed: {
    filteredByCat () {
      return this.businesses.filter((element) => {
        return element.cat.match(cat.name)
      })
    }
  }
1
  • I know I'm a little late to the party but I just wanted to add -for reference purposes- the link from the official Vue guide that states this limitation and also the way around it. Commented Jun 6, 2018 at 14:50

1 Answer 1

3

Use a method instead.

<ul>
    <li v-for="cat in categories">
        <ul>
            <li v-for="business in filteredByCat(cat)">{{business.name}}</li>
        </ul>
    </li>
</ul>

methods: {
    filteredByCat (cat) {
      return this.businesses.filter((element) => {
        return element.cat.match(cat.name)
      })
    }
  }

Alternatively you could use a computed to build the data structure you want to iterate.

computed:{
  businessesByCategory(){
    return this.categories.reduce((acc, category) => {
      acc[category] = this.businesses.filter(b => b.category == category)
      return acc
    }, {})
  }
}

And your new template would be

<ul>
  <li v-for="(value, key) in businessesByCategory"> {{key}}
    <ul>
      <li v-for="business in value">{{business.name}}</li>
    </ul>
  </li>
</ul>

Example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.