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"}}],
...