Filtering data in a table using Vue.js on the client side

I am facing an issue with filtering a table containing student details retrieved from a database using v-for. I am attempting to filter the table based on a specific field value. To begin with, I have three input fields located above the table, each bound by v-model to update a corresponding key-value pair in an array of filters. Below is the code for the computed studentsList that I am looping through.

  computed:{
filteredStudentList:function(){
  console.log(this.lastNameSearch);
  let filteredStudents =[]

  let filtersArray = [
    ['lastName',this.lastNameSearch ],
    ['firstName',this.firstNameSearch],
    ['studentID',this.studentIDSearch ],  

    ///avoiding comparing to null or empty searchBox     
  ]
  let filteredFiltersArray = filtersArray.filter(pair=>{
    return pair[1] !=null       
  })
  let dFilteredFiltersArray = filteredFiltersArray.filter(pair=>{
    return pair[1] !=""       
  })
  console.log(filtersArray);
  console.log(dFilteredFiltersArray);


  // add students to the filtered array, if they are not there already and all the searchBoxes are empty
  this.studentsList.forEach(student=>{
    if (dFilteredFiltersArray.length==0 && filteredStudents.indexOf(student)==-1){
    filteredStudents.push(student)
    }else{
        dFilteredFiltersArray.forEach(([q,a])=>{
          Object.entries(student).forEach(([k,v])=>{
        if( k==q){
          if(!v.match(a)){              
              console.log(student);
              filteredStudents.filter(i=>{
              return i !=student
            })
          }                      
        }             
      })
    })
    }        
  })
  console.log(filteredStudents);
  return filteredStudents
}    
   },

However, when I test it, regardless of the letter I type in the search box, it filters out all of the students. I am seeking assistance in identifying what is wrong with my code. Can someone help me with this issue?

Answer №1

let vm = new Vue({
  el: '#app',
  data: {
    firstNameSearch: "",
    lastNameSearch: "",
    studentIDSearch: "",
    studentsList: [
      {
        firstName: "Dan",
        lastName:"Ramsey",
        studentID: "1",
      },
      {
        firstName: "Jenna",
        lastName:"Combs",
        studentID: "2",
      },
      {
        firstName: "Jill",
        lastName:"Barron",
        studentID: "3",
      },
    ],
  },
  computed: {
    filteredStudentList: function() { 
      let filteredStudents = this.studentsList;
      if (this.firstNameSearch && this.firstNameSearch.length != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.firstName.toLowerCase().includes(this.firstNameSearch.toLowerCase());
        })
      }

      if (this.lastNameSearch && this.lastNameSearch.length != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.lastName.toLowerCase().includes(this.lastNameSearch.toLowerCase());
        })
      }

      if (this.studentIDSearch && this.studentIDSearch.length != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.studentID === this.studentIDSearch;
        })
      }
      return filteredStudents;
    }
  },
})
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <th>First Name</th>
    <th>Last Name</th>
    <th>ID</th>
    <tr v-for="student in filteredStudentList">
      <td>{{ student.firstName }}</td>
      <td>{{ student.lastName }}</td>
      <td>{{ student.studentID }}</td>
    </tr>
    <label for="firstNameSearch">First name</label>
    <input id="firstNameSearch" type="text" v-model="firstNameSearch"/>
    <label for="lastNameSearch">Last name</label>
    <input id="lastNameSearch" type="text" v-model="lastNameSearch"/>
    <label for="studentIDSearch">ID</label>
    <input id="studentIDSearch" type="text" v-model="studentIDSearch"/>
  </table>
</div>

I find this to be a simpler solution. Revised using a code snippet.

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

Is there a way to streamline the import process for material-ui components?

Is there a shortcut to condense all these imports into one line? As a newcomer to react, I've noticed that every component must be individually imported, especially when it comes to CSS components. Could you provide me with a suggestion on how to st ...

What is the best way to create an array containing dictionaries?

Hey there, I'm having an issue with my React.js code. Here's what I have: const array1 = [1, 4]; const map1 = array1.map(x =>{'x2': x * 2, 'x3': x * 3}); console.log(map1); // expected output: Array [{'x2': , 1, ...

Set the rowspan to 2 when the v-for index does not equal 2

This is the table I am working with: <table class="table table-condensed table-sm table-striped table-bordered" id="list"> <thead> <tr> <th v-for="(column, index) in columns" :key=& ...

Differences in Print Layout Between Chrome and Firefox when Viewing a PHP Website

I have been working on creating a print command to print a specific div, and I have managed to successfully run the print command using default methods like CTRL + P and also with a button click. The Issue: However, I have encountered a problem where the ...

Guide for implementing async/await in conjunction with the eval() function within JavaScript

I'm currently using the eval function to evaluate strings and adding await to it to ensure all values are obtained, but unfortunately the await is not functioning correctly. Here is a snippet of my code: if (matchCard.card.status != "notstarted& ...

How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services. My current approach involves the following code: // ...

Animate the expansion and shrinkage of a div instantly using jQuery

I am trying to create an animation effect using jQuery animate on a div element where it starts large and then becomes smaller. Here is the code I have written: $(this).animate({ opacity: 0, top: "-=100", width: "38px", height: "32px" }, 1 ...

Is storing Vuex state in sessionStorage a secure practice?

I am currently developing a web app with Vue.js/Vuex, but I am facing an issue where the state is lost when the user refreshes the page. I have attempted to address this by persisting some states in sessionStorage, however, I have come to realize that use ...

ways to utilize inline styling in react using javascript

When repurposing an array of React components, I am looking to modify the inline styles generated with them. How can I access and log the inline styles of a React component? UPDATE: see the code snippet below: const pieces = this.props.pieces.map((decl, ...

What is the most effective method for implementing a fallback image in NextJS?

Lately, I've been immersed in a NextJS project that involves utilizing the YoutubeAPI to retrieve video details, such as thumbnail URLs. When it comes to fetching a full resolution image, the thumbnail URL typically follows this format: https://i.yti ...

Enhance a Javascript object by dynamically introducing new elements

I am currently working on a webpage using HTML and jQuery. My goal is to create a form where users can enter an email address in a textbox, and when they click a button, the email should be added to an object that displays all the emails entered so far. Th ...

What is the best way to submit a Redux Form only if there have been changes made to any of the fields

I'm currently using Redux Form version 7.1.2, and I have a form that submits data when the user clicks the submit button. In the function assigned to handle the submission, I perform an action. However, I only want this action to be executed if there ...

What could be the reason why modifications made to $scope in a directive's link function do not appear on the user interface?

The AngularJS directives' link function causes changes to isolate scope data that are not reflected in the UI. Take a look at this example: var myApp = angular.module('myApp', []); myApp.directive('myDirective', function () { ...

Tailored design - Personalize interlocking elements

I am currently working on a custom theme and I am trying to adjust the font size of Menu items. In order to achieve this, I have identified the following elements in the tree: ul (MuiMenu-list) MuiListItem-root MuiListItemText-root If I want to modify th ...

The close button within the modal is malfunctioning even with the implementation of the on() function

My "show more" button triggers the modal to pop up, but when I click on the X button in the top left corner, it doesn't close as expected. However, clicking outside of the box or pressing the "esc" key does work. I suspect that the issue lies with th ...

Tips for stopping links in iOS web applications from launching in a new Safari tab

I am in the process of developing an HTML application specifically for iPads. To enhance user experience, I have added the web app to the homescreen using the "favorite" option. However, I encountered an issue where every internal URL opens in a new Safari ...

Is there a way to modify an element in an array in AngularJS without using splice?

I encountered a situation similar to the one described in this post here, where I not only want to retrieve an element but also change its name value. I came across a method that involves using splice: dataList.splice(index, 1); dataList.splice(index, 0, ...

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...

Error message: The variable "data" is not defined in next.js

Being new to React, I recently used getStaticprops to retrieve data from an API for a filter gallery project. However, I encountered an issue when trying to access the {props: data} outside of the blog function - it resulted in a Reference Error stating th ...

CSS- Strategically placing and centering images above specific keywords in (any) HTML content without disrupting the flow of text

My main objective involves dynamically inserting images above text on any given page using a content script. The challenge lies in maintaining the proper alignment of the text after adding the images. To achieve this, I surround the words where the image i ...