Issue experienced with Vue2 where utilizing a computed property to filter a nested v-for structure

I have a unique HTML challenge that requires me to iterate through an unconventional data setup. The information is retrieved in two separate parts from Firebase: one for categories and another for businesses. The structure of the data is as follows:

Businesses
    -UniqueFirebaseID
        cat: "food"

Categories
    -IniqueFirebaseID
        name: "food"

My goal is to loop through the data using the following approach (apologies for the lack of semantic markup):

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

I am currently attempting to create a computed property for filtering purposes. Although I have outlined my intentions below, I am unsure about the implementation. Any recommendations?

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

Answer №1

It is advised to utilize a method instead of the current approach.

<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 have the option to use a computed property to construct the desired data structure for iteration.

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

Your updated template would be as follows:

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

Here is an example link for reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does Vue 3 template display 101 instead of 1 when incrementing the number from 0?

Vue.createApp({ data() { return { counter: 0 } }, template: '<div>{{counter++}}</div>' }).mount('#root') Ultimately, the code above displays the number 101 on the page. Any insights into why this is happ ...

Utilizing jQuery for displaying or hiding list elements

To view all the code, click on this link: http://jsfiddle.net/yrgK8/ A section titled "news" is included in the code snippet below: <ul id="news"> <li><p>asfdsadfdsafdsafdsafdsafdsafdsafdsa</p></li> <li>&l ...

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

Jssor's dynamic slider brings a touch of sophistication to preview upcoming images

Incorporating the jssor nearby slider to create a nearly fullscreen display. The goal is to set the opacity of upcoming images to 0.25 when they are not in the main viewport, giving the edges of the upcoming and previous slides a slight transparency. < ...

Run JavaScript on every website when the page loads

After loading all or specific pages in the browser, I am looking to run JavaScript code (predefined code). Are there any browsers and plugins/components that allow me to achieve this? The manual method involves opening the console (e.g. firebug) and execu ...

What is the best way to transfer data in a JavaScript onclick event and then retrieve it in the click handler function?

I've been struggling with this issue for some time now. When researching the onclick JavaScript call, I noticed that sometimes it is written as onClick with a capital C, while other times it's simply onclick. The code I'm working on is part ...

Using jQuery to insert PHP code into a <div> element

In our capstone project, I'm looking to implement a dropdown calendar feature. I initially attempted to use ajax within a dropdown Bootstrap 4, but encountered issues with collapsing. As an alternative, I am considering utilizing the include method. A ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

Tips for automatically refreshing a Next.js application following an update in an external library

I have a monorepo containing two applications: The first is a Next.js web app The second is a UI library using Tailwind CSS and Microbundle Currently, the only way I can get the web app to recognize changes made in the UI library is by following these st ...

Here is a unique version: "In Javascript, users can trigger the function this.Something() from within this.img.onload by

I have some code that looks like this... Thing function () { var img = new Image; DoSomeStuff function() { //Code here that relies on my image being loaded... }; InitMe function(src) { this.img.onLoad = this.DoSomeStuff; ...

Implementing Vuetify data-table slots for different screen sizes: mobile breakpoints and body

In my Vue component using Vuetify data table, I have the following code: <template slot="body.append"> <tr> <th :colspan="6" class="text-right">Total:</th> </tr> < ...

Having trouble setting the focus on a text box following a custom popup

Presenting a stylish message box and attempting to focus on a textbox afterward, however, it's not functioning as expected. Below is the HTML code: <a class="fancyTrigger" href="#TheFancybox"></a> <hr> <div id="TheFancybox">& ...

How to implement setState within a Promise function using useEffect in React functional components with hooks?

I am struggling to set the value of a hook within a Promise function inside a useEffect(), and then store the returned promise value in the fruit hook so that it can be accessed in the return function of MyComponent() This is what I have attempted so far: ...

Trouble fetching asynchronous data in Next.js Higher Order Component

Currently, I am in the process of creating a Higher Order Component (HOC) that will fetch user data from my API and then provide props to the wrapped component. This will allow the component to redirect the user based on their role. Although the HOC appea ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

Block-level declarations are commonly used in TypeScript and Asp.net MVC 5

In my asp.net mvc5 project, I decided to incorporate TypeScript. I created an app.ts file and installed the nuget-package jquery.TypeScript.DefinitelyTyped. Here is a snippet of the app.ts code: /// <reference path="typings/jquery/jquery.d.ts"/> cl ...

Apps hosted on Heroku are restricted from accessing CORS, even within the platform's domain

I've been struggling with this problem for a while now. My Nuxt app and service are both hosted on Heroku. After ditching cors(), I added the following code: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", '*&ap ...

end the node.js automated testing process

I'm currently using Jasmine and Zombie JS to create automated tests. I have integrated Drone.io for Continuous Integration, and the tests are executing successfully. However, there seems to be an issue where after passing the tests, the process does n ...