Filtering Array Elements in Vue JS: A Step-by-Step Guide

In my Vue Js 2.0 application, I am working on filtering elements in an array format. Here is the code snippet:

const search = this.search_by_name.toLowerCase()
const searchContact = this.search_by_contact.toLowerCase()
return this.meetings
    .map(i => ({
        id: i.interaction.id,
        client_name: i.client.name,
        contactName: i.contacts_association,
    }))
    .filter((item) =>
        item.client_name.toLowerCase().includes(search)
    )

I am facing an issue with filtering based on

item.contactName.first_name.toLowerCase().includes(searchContact)
. The error being thrown is:

TypeError: item.contactName.toLowerCase is not a function

The structure of my contacts_association data is as follows:

"contacts_association":[
    {
        "id":431,
        "first_name":"Nikunj",
        "last_name":"Doshi",
        "address":"602-603, 6th Floor, Dalamal House,Nariman Point",
        "city":"Mumbai",
        "state":"Maharashtra",
        "country":"India",
        "pivot":
            {
                "interaction_id":139,
                "contact_id":431,
                "company_id":160,
                "created_at":"2017-09-23 16:42:56",
                "updated_at":"2017-09-23 16:42:56"
            },
        "company":[
            {
                "id":160,
                "name":"Bay Capital Investment Managers Pvt Ltd",
                "address":"602-603, 6th Floor, Dalamal House,Nariman Point",
                "city":"Mumbai",
                "state":"Maharashtra",
                "country":"India",
                "type":"Investor",
                "sub_type":"FII",
                "is_client":0,
            }
        ]
    },
    {
        "id":431,
        "first_name":"Vikash",
        "last_name":"Kumar",
        "address":"602-603, 6th Floor, Dalamal House,Nariman Point",
        "city":"Mumbai",
        "state":"Maharashtra",
        "country":"India",
        "pivot":
            {
                "interaction_id":139,
                "contact_id":431,
                "company_id":160,
                "created_at":"2017-09-23 16:42:56",
                "updated_at":"2017-09-23 16:42:56"
            },
        "company":[
            {
                "id":160,
                "name":"Investment Managers Pvt Ltd",
                "address":"Nariman Point",
                "city":"Mumbai",
                "state":"Maharashtra",
                "country":"India",
                "type":"Investor",
                "sub_type":"FII",
                "is_client":0,
            }
        ]
    }
]

I need help in filtering based on both first_name and last_name.

Answer №1

So essentially what you're saying is that contactName represents an array of contacts rather than just a single one, and your goal is to find all meetings that have at least one contact in contactName with a name that matches searchContact?

You can attempt the following code (not yet tested):

.filter(item =>
  item.client_name.toLowerCase().includes(search) &&
  item.contactName.some(c =>
    (c.first_name + ' ' + c.last_name).toLowerCase().includes(searchContact)
  )
)

Additionally, it is important to note that mixing camelCase and snake_case for contactName and client_name, respectively, can be confusing. It would be beneficial to choose one consistent style.

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

Navigate to the middle of a DIV container in Angular 7

Is there a way to programmatically scroll to the center of my element on both the Y and X axes when a specific function is executed? My HTML structure includes the following (I am aiming to scroll to the middle of #viewport): </div> <div # ...

Instructions for receiving user input and displaying it on the screen, as well as allowing others with access to the URL to view the shared input provided by the original user

<h1>Lalan</h1> <input type="text" name="text" id="text" maxlength="12"> <label for="text"> Please enter your name here</label> <br><input type="submit" value ...

What is the way to activate Dynamic ng-model from a controller?

I am implementing a loop in my HTML code where each iteration dynamically creates a model. Here is an example of how the loop looks: <tr ng-repeat="item in voucherItems"> <td><input type="text" ng-model="this['id-' + $index ...

JavaScript file isn't being called by index.html

I am working on establishing a basic client/server connection using node.js modules along with a straightforward HTML page. The content of the HTML page is as follows: <script type="text/javascript" src="index.js"></script> The index.js fi ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

What could be causing the HTML content to not display when the code is executed?

I've recently started using Visual Studio Code for my project. I am able to build my code without any errors, but when I run it, the HTML content does not display properly - only the CSS styling for the header and footer is visible. I have tried click ...

What steps should be taken to properly assess an AngularJS provider setup?

My provider definition looks like this: (function(angular) { angular.module('myModule', []) .provider('myService', function () { var service = {}; service.configureSomething = function () { }; service.$get = function () { ...

Having trouble with jQuery show/hide not functioning properly?

My website has a sub-menu section with a shopping cart icon. When a user hovers over the icon, it reveals a hidden cart section. The user can then move the mouse into the cart section to remove items. The problem I'm facing is that if a user displays ...

Create and transmit an array of JSON objects

I need help with defining and sending a JSON object array. While I've managed to define a single JSON object, convert it into a string, and send it, I'm stuck on how to do the same for an array of objects. It seems like there might be a simple so ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

Use the Google Maps API to dynamically add a marker via AJAX once the map has been initialized

Although I have come across similar questions with related titles, none of the answers quite fit my needs. Here is the problem I am facing: I'm working on printing a map that contains multiple markers generated from a database. Below the map, there ...

Passing a custom property from a parent component to a child component in VueJS using property

One of my components is called controls: <li class="controls__item" v-if="options[0].save == 'show'"> <button class="btn" :options[0].saveAttr>Save</button> </li> I'm facing an issue with displaying an attribute ...

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

The hover feature on my website is making the picture flicker

I am experiencing an issue with a map on my website that contains four colored squares. When I hover over one of the squares, the image of the map changes to show the route corresponding to that color. However, this causes the image to shift position and i ...

error in three.js occurs when attempting to load .obj files

I've been encountering issues with OBJ files that I've downloaded from the internet. All of these files render like this: View Obj File Pic I'm using the standard OBJLoader for rendering. var loader = new THREE.OBJLoader(); loader.load( ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...

The final DOM is not loading properly when using Jest and React Testing Library during page initialization

I'm currently working on testing my React application with Jest and React Testing Library. During this process, I am attempting to verify that the login page displays a specific message once it has fully loaded. Upon initial loading of the login page, ...

JavaScript Recursive Function for Generating FancyTree JSON Structure

I'm currently building an array of JSON objects for FancyTree (https://github.com/mar10/fancytree/wiki/TutorialLoadData). My JSON source is from the Jira REST service, and its structure can vary widely. Therefore, the code to construct the array of JS ...

Calculate the number of characters in the input and increase a variable by one every x characters

Currently, I am incorporating AngularJS into a new project and faced with the task of counting the length of a textarea. Adding up the total number of "pages" in the messaging app every 160 characters while decreasing if text is removed. Obtaining the len ...

Is there a way to determine if a field has been interacted with and meets validation criteria using VeeValidate?

I'm attempting to retrieve the validation flags from a computed property: computed: { isFormValid() { let isValid = this.$validator.fields.some(field => { console.log(field.flags); return field.flags.touched || field.flags.invali ...