Using Vue.js to apply a filter on a multidimensional array within a computed function

Seeking help with implementing a filter search feature for my Tagging Tool Component that has 3 different levels of priority. Is it possible to access tags[n] in the computed function tagsFilter?

Check out the current version: https://jsfiddle.net/hej7L1jy/26/

I want to replace v-for="tag in tags[n]" with: v-for="tag in tagsFilter". Currently, I'm encountering a

TypeError: this.tags.filter is not a function

Open to suggestions and ideas!

Vue.js Template:

<div id="app">
  <input id="input-search" type="text" class="form-inline pull-right" v-model="textSearch" placeholder='Search...'>
  <div v-for="n in prios">
  <h3>{{n}} tag priority</h3>
    <ul v-if="tagsFilter && tagsFilter.length">
      <li :class="'tagPriority-'+n" v-for="tag in tagsFilter">
        <label class="checkbox-inline"><input name="tags[]" type="checkbox" v-model="tagSelected" :value="tag.id"> {{tag.title}}</label>
      </li>
    </ul>
  </div>
</div>

Vue.js component:

new Vue({
    el: '#app',
        props: {
            selectedTags: {
                type: Array
            }
        },
        data() {
            return {
                prios: [ 1, 2, 3 ],
                tagSelected: [],
                tags: [],
                textSearch: ''
            }
        },
        computed: {
            tagsFilter: function() {
                var textSearch = this.textSearch;
                return this.tags.filter(function(el) {
                    return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
                });
            }
        },
        created: function () {
            this.tagSelected = this.selectedTags;
            this.tags = {"1":[{"id":9,"title":"Auto"}],"2":[{"id":8,"title":"Elektroauto"}],"3":[{"id":10,"title":"BMW i3"},{"id":11,"title":"Opel Ampera"},{"id":12,"title":"Renault TWIZY"}]};       
        }

});

Answer №1

When defining your data, you set up the tags like this:

data() {
    return {
        tags: [],
    }
},

However, in the created callback function, you override this.tags:

created: function () {
    this.tagSelected = this.selectedTags;
    this.tags = {"1":[{"id":9,"title":"Auto"}],"2":[{"id":8,"title":"Elektroauto"}],"3":[{"id":10,"title":"BMW i3"},{"id":11,"title":"Opel Ampera"},{"id":12,"title":"Renault TWIZY"}]};       
}

This changes it into an object without a filter method.

Utilizing a computed property for filtering

Your template code:

<li :class="'tagPriority-'+n" v-for="tag in tags[0]">

Can be updated to:

<li :class="'tagPriority-'+n" v-for="tag in tagsFilter[n]">

And your computed property:

computed: {
    tagsFilter: function() {
        var textSearch = this.textSearch;
        return this.tags.filter(function(el) {
            return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
        });
    }
},

You can modify it to:

computed: {
    tagsFilter: function() {
        var textSearch = this.textSearch;
        var filteredTags = {};
        var tags = this.tags;
        Object.keys(this.tags).forEach(function(key) {
            filteredTags[key] = tags[key].filter(function(el) {
                return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
            });
        });
        return filteredTags;
    },
},

This approach iterates over each property of this.tags and creates a filtered version of each within filteredTags.

Check out the demo JSFiddle here.



Alternate method using a function for filtering

If you want minimal code changes, consider converting your computed property to a method with an argument:

<li :class="'tagPriority-'+n" v-for="tag in tags[0]">

Update it to:

<li :class="'tagPriority-'+n" v-for="tag in tagsFilter(n)">

And tweak your computed as follows:

methods: {
    tagsFilter: function(i) {
        var textSearch = this.textSearch;
        return this.tags[i].filter(function(el) {
            return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
        });
    },
},

Explore the demo JSFiddle here.

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

Images will only be displayed if the optional html parameter is included; otherwise, they will be hidden

In my parent component, there is an image displayed at a specific path (note: the image is already stored in my project). This path can optionally have additional parameters. If the For instance, The image is visible (image) when the HTML path is: ww ...

Adding a custom property to a React component

Currently, I am facing an issue while attempting to modify an MUI component. Everything works smoothly until I execute the build command, at which point it fails. I have experimented with a few variations of this, but essentially I am looking to introduce ...

Issue importing legacy JavaScript class_1.class as a constructor in TypeScript with Webpack

I am currently in the process of transitioning a project from JavaScript to TypeScript. The original JavaScript code is legacy and was not structured for exporting/importing, but rather concatenated together. I am facing challenges when trying to import th ...

Sending dynamic information to bootstrap's modal using props in VueJS

I'm currently working on a personal project and encountering an issue with the bootstrap modal. My project involves a list of projects, each one contained within a card element. The problem arises when I attempt to display details for each project by ...

What is the best way to connect click events with ExtJS template elements?

Is there a way to assign a click event to each link tag without directly embedding onclick=.... in the XTemplate code? new Ext.XTemplate( '<ul>', '<tpl for="."><li><a href="#{anchor}">{text}</a></li& ...

Tips for sending <p> data to a router function with HTML

I am currently working on a page where users are presented with a list of unverified accounts, each containing its own form element. Each form has a "submit" button that triggers a POST call to /verify. However, I am facing an issue where the data within t ...

Unicef's animated web content

Looking to learn more about gate animation and zoom page transition on the Unicef website? I want to incorporate these cool animations into my own project. Can someone provide me with a "keyword" or point me in the right direction to find information on ...

What is the method for inserting a horizontal line into a highcharts js graphic?

add your own description This is the method to achieve it! I can accomplish this without using css positioning. ...

Manipulating div positions using JQuery and CSS

Whenever I hover over the #HoverMe div, a hidden #hidden div appears, and when I unhover it, the hidden div disappears again. The #hidden div contains a sub-div that functions like a dropdown list. The #hidden div is styled with position: absolute;. How ca ...

Issue with Vuetify's v-file-input: "onchange" event is functioning correctly, however, the event object is not

Could you please review the code snippet below? The issue I am facing is that while the input element functions correctly, the v-file-input seems to be causing problems: <v-file-input accept=".json" ref="loadedFile" label="Upload file" @change= ...

Tips for safely using Buefy's Dialog component with custom user input to prevent cross-site scripting attacks

When using Buefy's Dialog component, it requires a prop called message, which should be a string and can potentially include HTML. I want to incorporate template values into the string securely to prevent XSS vulnerabilities. Unsafe Example Currently ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Create a dropdown menu using a PDO query to populate the selectable options

I need to create a Select List that dynamically populates items/information from a Query. I understand the importance of updating the select list every time the database is updated, so JQuery is required for this task. Although I have limited experience wi ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Issue with triggering a modal while simultaneously closing another one

Let's consider this situation. I currently have a modal called Modal A, which has 2 buttons in the footer: Save and Close. When I click on the "Save" button, my intention is to close Modal A and open Modal B. The code that achieves this functionality ...

Utilizing conditional statements in React js to showcase a distinct component

I am looking to create a function or conditional statement that dynamically displays different components based on whether the user has purchased products. If the user has bought products, I want to display the product components; if not, I would like to s ...

What is the best way to change an HTML class using PHP?

I'm currently facing a challenge with my "Newsletter Subscription Form". I rely on MailChimp for sending out newsletters and have successfully set up a custom PHP file to redirect visitors after they enter their email. Here's the step-by-step pr ...

Tips for directing your attention to a specific cell within a grid after inputting a value into a textBox

I am looking to navigate to a specific cell within a grid by entering the cell number into a textBox. Upon typing any number in the textBox, it should automatically focus and scroll to that particular cell in the grid. For example, if I type 601 in the te ...

What is the best way to convert a JSON object back into an object with its own set of methods?

Currently, I have a JavaScript object with multiple methods attached via prototype. When I serialize the object to JSON, only the property values are saved, which is expected. It wouldn't make sense to save the methods as well. Upon deserialization ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...