Filtering an Array in VueJS Based on User Input

Currently, I am working on a application where my goal is to filter an array based on user input from a form.

The issue I am facing is that the array named autocomplete is not being populated with visitors that match the query of the first name.

This is a snippet of my HTML code:

<input class="input" placeholder="First Name" v-model="visitor.first" @keyup.enter="searchVisitors">

And here is my Vue Instance code:

new Vue({

  el: '#app',

  data: {
    previousVisitors: [],
    autocomplete: [],
    visitor: {}
  },

  mounted() {
    axios.get('/visitors/all').then(response => this.previousVisitors = response.data);
  },

  methods: {

      searchVisitors(){
        var q = this.visitor.first;
        this.autocomplete = this.previousVisitors.filter(item => {return item.firstName === q});
        console.log(this.autocomplete);
      }
   }
});

I have verified that the response from the axios call, which populates the previousVisitors array, contains the firstName of each previous visitor.

What could be the mistake in my implementation?

Answer №1

Your v-model is currently set to visitor.first, but you are filtering based on firstName.

To correct this, update your code to use

v-model="visitor.firstName"
.

Additionally, there are some potential issues that may cause problems in the future. Firstly, you are dynamically adding a value to visitor, which could lead to reactivity issues. It's recommended to initialize that value properly.

data: {
  ...
  visitor:{firstName: ''}
}

Furthermore, it would be better to utilize a computed value for the filter. Below is a complete example showcasing this approach.

console.clear()

const visitors = [{
    firstName: "bob"
  },
  {
    firstName: "mary"
  },
  {
    firstName: "susan"
  },
  {
    firstName: "Phillip"
  },

]


new Vue({

  el: '#app',

  data: {
    previousVisitors: [],
    visitor: {
      firstName: ''
    }
  },

  mounted() {
    // axios.get('/visitors/all').then(response => this.previousVisitors = response.data);
    setTimeout(() => this.previousVisitors = visitors)
  },
  computed: {
    autocomplete() {
      return this.previousVisitors.filter(v => v.firstName === this.visitor.firstName)
    }
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b4b7a782f0ecf0ecf4">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <input class="input" placeholder="First Name" v-model="visitor.firstName"> {{autocomplete}}
</div>

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

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

Guide on parsing a JSON object in JavaScript

One issue I'm facing is that my controller method returns a string representation of a jsonArray using the jsonArray.toString() function. Below is the corresponding ajax method: function loadPropertyFile(url) { $.ajax({ type: "GET", url: url, ...

The system is unable to retrieve the value of the property which is set as null

I'm trying to figure out how to store the input value of name_enter into the variable userName. However, every time I attempt this, I encounter the following console error: Uncaught TypeError: Cannot read property 'value' of null function ...

Locating Elements in Protractor: Exploring Nested Elements within an Element that is Also a Parent Element Elsewhere on the Page

<div class="base-view app-loaded" data-ng-class="cssClass.appState"> <div class="ng-scope" data-ng-view=""> <div class="ng-scope" data-ng-include="'partial/navigation/navigation.tpl.html'"> <div class="feedback-ball feedback- ...

Select a different radio button to overwrite the currently checked one

I am facing a situation where I have two radio buttons. The default checked state is one of them, but I want to change that and make the other one checked by default instead. Here is the HTML code: <div class="gui-radio"> <input type="radio" v ...

Utilize React to update the state of arrays in functional components

Need help with updating the cars array in my React app. When I click on the Add button, a new object is added to the updatedCars array but the state of cars does not get updated. Even after adding a new object to the array, the initial state remains uncha ...

Saving a collection of unique identifiers in Firebase

Struggling to find a solution for organizing Firebase data: Each user has posts with generated IDs, but how do I store these IDs in a user node efficiently? Currently using string concatenation and treating them like a CSV file in my JS app, but that feel ...

Adding the data from an ajax object response to an array

I'm encountering an issue where my Ajax response is not being properly looped through each object and pushed into the array. I've been stuck on this problem for quite some time now. The Ajax response looks like this... {type:'blog_post&apo ...

Using JavaScript within HTML documents

Need help with inserting JavaScript code from Google: <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1362706866260-0'); }); </script> into existing JavaScript / HTML code: va ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...

How to filter jQuery DataTables by column using comparison operators

Recently, I've been utilizing the amazing DataTables jQuery plugin along with the filter plug in. But now, I find myself pondering if there's a way to filter table columns by row using a comparison operator (such as '<', '>', ...

Guide on adding checkboxes for each child component in a Vue ads table

<vue-ads-table :columns="fields" :rows="items" :selectable="true" @row-selected="onRowSelected" class="my-table" ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

I'm looking to display 9 images on a single page that rotate every 5 seconds between 3 different images. While I can figure out how to display one image easily, I'm

<script type="text/javascript"> var currPic = 1; var totPics = 9; var keepTime; function setupPicChange() { keepTime = setTimeout("changePic()", 5000); } function changePic() { currPic++; if (currPic > totPics) currPic = 1; var f ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...

How to Transfer Information Between Two React Components

I recently started learning React and I'm not sure how to approach this task. Basically, I have a list of cars and when the user clicks on each car, it should display detailed information about that specific car in a full-page slide. This is my curr ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

What is the best way to transform a standard select input into a React select with multiple options?

Is it possible to transform a regular select dropdown into a multiple select dropdown in React, similar to the one shown in this image? I'm currently using the map method for my select options. https://i.stack.imgur.com/vJbJG.jpg Below is the code s ...

Turning a Vue object back into a regular JavaScript object - the step-by-step guide!

Is there a way to revert objects that have been transformed into Vue.js's reactive system back to their original state as normal objects? ...