Sort data by various categories using Vue.js

I need help filtering my JSON data based on multiple categories using Vuejs, specifically with Vue 3 and collect.js.

Here's the template I'm working with:

<select v-model="selectedCategory" multiple>
    <option :value="null">Choose category</option>
    <option v-for="category in categories" :key="category.id" :value="category">{{ category.name }}</option>
</select>
<div v-for="project in filteredProjects" :key="project.id">
    <h6>{{ project.name }}</h6>
    <small>{{ project.category.name }}</small>
</div>

And here is the script part of my code:

import collect from "collect.js";
export default {
    data() {
        return {
            projects: [{id: 1, name: "Lorem ipsum", category: {id: 1, name: "Website"}}, {id: 2, name: "Sit amet", category: {id: 2, name: "App"}}],
            categories: [{id: 1, name: "Website"}, {id: 2, name: "App"}],
            selectedCategory: null,
        };
    },
    computed: {
        filteredProjects() {
            let projects = this.projects;
            if (this.selectedCategory != null) {
                projects = projects.filter((project) => {
                    return collect(project.category).contains("id", this.selectedCategory.id);
                });
            }
            return projects;
        },
    },
};

Any advice or suggestions on how to improve this?

Update: Keep in mind that a single project can have multiple categories like shown below:

...
projects: [{id: 3, name: "Lorem ipsum dolor", category: {id: 1, name: "Website"},{id: 2, name: "App"}}],
...

Answer №1

Successfully resolved:

this.selectedCategory.filter((category) => {
    projects = projects.filter((project) => {
        return collect(project.software).contains(
            "id",
            category.id
        );
    });
});

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

Tips for retrieving the selected option from a dropdown menu

I have a dropdown menu with checkboxes that can be selected using SumoSelect. Here is the markup for the dropdown menu: <select multiple="multiple" name="somename" id="uq" class="select"> <option value="volvo">Volvo</option> <o ...

What is the best way to identify when a page has been refreshed in Reactjs?

Imagine a set of pages with steps: 1, 2, and 3. If a page reloads during the second or third step, it must be directed back to the first step. Is there a way to identify when a page has been reloaded? ...

Issue: Failed to locate module @angular/core

When attempting to run an Angular 4 application, I consistently encounter the following error: ERROR in Could not resolve module @angular/core There are no additional errors present. There are no dependency issues whatsoever as @angular/core is located i ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

What is the best way to relay error messages to other sections of the form?

I am currently tackling a challenge with Vue and Laravel. The issue at hand involves an error class that I have created for a form which interacts with 3 different components. For instance, there is the base form component and then a child component of th ...

Dealing with two form submissions using a single handleSubmit function in react-hook-form

I have a React app with two address forms on one page. Each form has its own save address function that stores the address in the database. There is a single submit button that submits both fields and redirects to the next page (The plus button in the circ ...

What is the maximum number of rows that Handsontable can handle at once?

Issue encountered in queued task: Security check failed - Too many TRs. Please specify table height to enable scrollbars. at WalkontableTable._doDraw (client/libs/handsontable-0.10.5/jquery.handsontable.full.js?37b46fd989b9a974c3501865b51effd7adec37e4:1285 ...

What specific URL should be included in a JavaScript ajax request?

As I delve into creating a JSON file using an ajax request in javascript, confusion strikes when it comes to determining the appropriate URL. With no previous experience working server side and relying on WAMP server 3.0.6 to host my project-in-the-works ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

What is the best way to separate a string using a comma as a delimiter and transform it into a string that resembles an array with individual string elements

I am in search of a way to transform a string, such as: "one, two, three, four" into a string like: "["one", "two", "three", "four"]" I have been attempting to devise a solution that addresses most scenarios, but so far, I have not been successful. The ap ...

Developing a single page that caters to various users' needs

Greetings to all my friends, As a front end developer, I am in the process of implementing a dashboard for a project that involves different users with varying permissions. Each user should only have access to certain parts of the page, resulting in some ...

Which symbol or character corresponds to the public "get symbol" method?

While going through some Typescript code, I came across a line that is giving me trouble to understand. const symbol = Symbol.for('symbolname'); class Something { public get [symbol]() { return true; } ... } I am confused abou ...

Set JSON Value Session

In the table, there is an option to edit certain entries using a button. I have developed a function that retrieves JSON data and populates the table with it. This process happens before any other actions. Once the data is loaded, my goal is to create a c ...

Tips for examining a rate-limited HTTP request function

I am trying to test a naive rate limiter I implemented in Node.js for making HTTP requests to an external service. The service has a limit of 10 requests per second, and I am facing timing issues with my current implementation. Despite being aware of the i ...

What is the best way to transfer information from a view to a controller in Laravel using AJAX?

I am facing an issue with sending data from the view to the controller in Laravel version 7 I am sending data from a form and ul li elements I have an array of data in JavaScript Here is my HTML code: <ul name="ali" id="singleFieldTags&q ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Obtaining the client's IP address using socket.io 2.0.3: a comprehensive guide

Currently, I am facing a challenge using socket.io v2.0.3 in my node.js server as I am unable to retrieve the client's IP address. Although there are several suggestions and techniques on platforms like stackoverflow, most of them are outdated and no ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...

React Redux component fails to reflect changes in props after store update

Something odd is happening with my React Native component's props. They used to update after the redux store updated, but suddenly one day they stopped working. The dispatch is functioning correctly, and the store is updating state without any mutati ...