Using Filters in VueJs

I am currently working on creating a small Vue.js 2.0 application where I am utilizing the v-select component from here. The data format that I am dealing with looks something like this:

{
    "model":
        [
            {
                "id":1,
                "salutation":"Mr",
                "first_name":"Rahul",
                "last_name":"Bashisht",
                "number":"9876521102",
                "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0674676e736a466f656f656f6467686d2865696b">[email protected]</a>",
                "company":
                    {
                        "id":1,
                        "name":"ICICI Bank",
                        "is_client":1,
                    }
            },
            {
                "id":2,
                "salutation":"Mr",
                "first_name":"Vikash",
                "last_name":"Pandey",
                "number":"0987654345",
                "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8aeb1b3b9abb098b0bcbebbf6bbb7b5">[email protected]</a>",
                "company":
                    {
                        "id":2,
                        "name":"HDFC Bank",
                        "is_client":0,
                    }
            }
        ]
}

After setting this data to a variable model, I am attempting to filter it based on client = 1 in a computed property as follows:

contactClients: function() {
    if(this.model)
    {
        return this.model
            .filter(f => (f.company.is_client == 1))
            .map(d => ({label: d.first_name+' '+d.last_name+' - '+d.company.name, value: d.id}))
    }
},

Next, I am using this filtered data in the v-select options section like this:

<v-select multiple :options="contactClients" v-model="clientParticipants"></v-select>

Furthermore, I have another v-select that should display company names where is_client is true. To achieve this, I have a dataset of companies structured as shown below:

{
    "model":
        [
            {
                "id":1,
                "name":"ICICI Bank",
                "is_client":1,
            },
            {
                "id":2,
                "name":"HDFC Bank",
                "is_client": 0,
            },
            {
                "id":3,
                "name":"BNP Paribas",
                "is_client": 0,
            },
            {
                "id":4,
                "name":"Barclays Bank",
                "is_client": 1,
            }
        ]
}       

This company data is stored in a variable called companies and is filtered as follows:

clients: function () {
    if(this.companies)
    {
        return this.companies
            .filter(f => f.is_client == 1)
            .map(d => ({label: d.name, value: d.id}))
    }
} 

The v-select in this case will contain:

<v-select :options="clients" v-model="summary.client"></v-select>

My goal is to introduce an additional filter based on the selection made in the contactsClients list. If any items are selected in the first list, the second list should only display companies related to those selections. Otherwise, the default options should be displayed with a simple is_client filter as it currently does. Since multiple selections can be made in the contactClients list, I am unsure how to proceed with filtering these elements. Any guidance would be greatly appreciated.

Edit: Codepen Link

Answer №1

Perhaps this solution can assist you in resolving your issue.

getClients: function() {
  if (this.model) {
    return this.model.filter(f => f.company.is_client == 1).map(d => ({
      label: d.first_name + " " + d.last_name + " - " + d.company.name,
      value: d.id,
      companyId: d.company.id
    }));
  }
},
retrieveAllClients: function() {
  var self = this;
  var results = [];
  if (this.companies) {

    if (this.clientParticipants.length) {
      console.log(this.clientParticipants)
      this.clientParticipants.forEach(function(cc) {
        self.companies.forEach(function(c) {
          if (cc.companyId === c.id) {
            results.push(c);
          }
        });
      });
      return results.map(d => ({ label: d.name, value: d.id }));
    } else {
      return this.companies
        .filter(f => f.is_client == 1)
        .map(d => ({ label: d.name, value: d.id }));
    }
  }
}

View an example 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

After integrating Vue + Inertia into my Laravel 10 project, I encountered an issue where I am receiving an error stating 'autocomplete not a function' when trying to load a Vue

BACKGROUND: My Laravel application is well-established and developed using Laravel, Blade, Javascript, and JQuery. Loading a blade view from the Laravel section of the site does not show any errors in Chrome dev tools. It's important to note that I ut ...

Determine all subarrays within two integer arrays whose sum matches a specified target number

Given two integer arrays, find all subarrays whose sum equals a specified target number. For example, if array1 = [1,2,3,4] and array2 = [7,3,4], with the sumToFind being 5, the function findSubArrays(array1, array2, num) should output [[1,4],[2,3]]. I in ...

In the realm of JavaScript, the localeCompare() string method is more than willing to accept the presence of 'undefined' as a valid parameter for 'locale', while opting to outright reject any instance of

I have discovered a method to sort strings naturally const rows = ['37-SK', '4-ML', '41-NP', '2-YZ', '21', '26-BF']; console.log(rows.sort((a, b) => a.localeCompare(b, undefined, { numeric: tru ...

What are some of the methods that can be used with the Facebook API to interact with the Like button

I am working on developing a JavaScript script that will automatically click on all the LIKE buttons for posts loaded on Facebook in the Chrome browser. Input: "" Or any other FB page,Groups,Profiles Step1: I will scroll down to load all the posts S ...

When I try to start the editor with HTML content using the convertFromHTML method, I encounter an error stating that

I am encountering an error when trying to initialize my Editor state with a HTML markup. at renderToString (/home/al/Documents/node/admin-next/node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27) at render (/home/al/Documents/node/admin ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...

After clicking on a specific href element with a designated class, trigger the display of a custom dialog styled using CSS

I recently added a unique class to certain links on my website. When these specific links are clicked, I want them to trigger a customized dialog box. My goal is to modify the CSS of this special dialog box. Only links with this particular class should ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

Ways to conceal various components while showcasing just a single element from every individual container

I am looking to only display specific span elements within their parent container (coin) while hiding the rest. The desired output should show only "1" and "first" while the other spans are hidden. <div class="types"> <div class=" ...

Is there a way to transfer the value from one directive to another directive template and access it in a different directive's scope?

I attempted to pass the directive attribute value to a template ID, which can then be used in another directive. Below is my index.html code: <my-value name="jhon"></my-value> Here is the JavaScript code: .directive('myValue',func ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...

Ways to verify if the user has inputted a typeahed value

My code snippet looks like this: var students = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('fullName'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

Is there a way to update a single element within an array without triggering a refresh of the entire array?

Is there a way to prevent the component from rerendering every time new data is input? I attempted to memoize each cell but I am still facing the same issue. Any suggestions on how to accomplish this? import React, { useState, memo } from "react&quo ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...

Sending dynamic data from PHP to jQuery flot pie chart

In my PHP code, I have defined 3 variables. $record = "283-161-151"; $rec = explode("-", $record); $win = $rec[0]; $draw = $rec[1]; $loss = $rec[2]; The variables $win, $draw, and $loss are displaying correctly, indicating they are working as intended. ...

The error message "Cannot read property 'addEventListener' of undefined" occurred while trying to register the service worker using `navigator.serviceWorker.register('worker.js')`

I'm grappling with a JavaScript issue and need some help. You can find the demo of the functioning script by the author right here. I've implemented the same code as displayed on his demo page. I've downloaded the worker.js file and ...

Phonegap app: The function in the AngularJS controller is only executed when called twice

I am currently developing a phonegap app using angularJS, and I have encountered an issue with a function in one of my controllers. Here is how my controller looks like: function NavCtrl($scope,navSvc) { $scope.slidePage = function (path,type) { ...

Utilizing Hyperlinks in jQuery DataTables Cell with Data Pulled from Mysql Table

I have a question that builds upon the one before it: How to display a hyperlink in a cell with jQuery DataTables There is also a Fiddle link provided My current query revolves around implementing hyperlinks when fetching data from a MySQL database table ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...