vue utilize filtering to search through a nested array of objects within a parent array of objects

After making an API call, I receive JSON-formatted data with a specific structure like this:

data = [ { name: 'John', 
           school:[ { school_name: 'Harvard', date_attended: '2017-05-23' },
                    { school_name: 'UCLA', date_attended: '2012-03-13' } ] 
         },
         { name: 'Harry', 
           school:[ { school_name: 'Stanford', date_attended: '2015-09-18' }] 
         },
         ....
       ]

Within the context of my project, I have a computed property referred to as filterSearch

computed: {
    filterSearch() {
        if(this.search == '') {
                return this.teachers_list;
            } else {
                return this.teachers_list.filter( hero => {
                return hero.name != null 
                    
                   ?
                    
                   !this.search || hero.name.toLowerCase().includes(this.search.toLowerCase()) 

                   : ''
                })
            }
    }
}

The current implementation works perfectly when searching for names. However, I am now looking for a way to modify it such that it can also effectively search based on the school name field.

Answer №1

You must add an additional filter within the existing filter function.

applyFilter() {
    if(this.searchTerm != '') {
        return this.students.filter( student => {
            student.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
            student.classes.filter(c => c.toLowerCase().includes(this.searchTerm.toLowerCase())).length > 0
        })
    }
    return this.students;
}

Answer №2

I have enhanced the functionality of filterSearch() and added a new method called filterSearchBySchoolName()

filterSearchByName() {
  if (this.search === '' || !this.search) {
    return this.teachers_list
  } else {
    return this.teachers_list.filter(
      (hero) =>
        hero.name?.toLowerCase()
          .includes(this.search.toLowerCase())
    )
  }
},
filterSearchBySchoolName() {
  if (this.search === '' || !this.search) {
    return this.teachers_list
  } else {
    return this.teachers_list.filter((hero) =>
      hero.school?.some(
        (school) =>
          school.school_name
            .toLowerCase()
            .includes(this.search.toLowerCase())
      )
    )
  }
}

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

A custom name for mapGetters in Vuex when the namespace is set to true

Is there a specific syntax for mapGetters when wanting to assign a custom name and use it in the template instead of the actual getters name? const store = createStore({ modules: { prods: productsModule, cart: cartModule } }); Here is an examp ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...

Sorts through nested arrays to uncover distinctive product assortments

Currently, I am in the process of developing a website using Next.js and Shopify. My objective is to create a page that displays all collections matching a specific productType. To achieve this, I have been exploring ways to extract this data from the Gra ...

Tips for formatting a lengthy SQL query in a Node.js application

Currently, I am facing a challenge with a massive MySQL select query in my node.js application. This query spans over 100 lines and utilizes backticks ` for its fields, making me uncertain if ES6's multi-line string feature can be used. Are there any ...

What is the best method for choosing one specific item from an array within a data object and transferring it to a different component?

After retrieving data using axios and passing it to a Bootstrap table, I have set up a click event in my computed properties for the nameOfPerson field. This event allows users to click on a person's name and open a modal that displays the correspondi ...

Dots are used to indicate overflow of title in React Material UI CardHeader

Is there a way to add ellipsis dots to the title in my Cardheader when it exceeds the parent's width (Card width)? Here is what I have attempted so far: card: { width: 275, display: "flex" }, overflowWithDots: { textOverflow: &apo ...

Changing a C# Datetime type to a Date using javascript in an ASP.NET MVC Razor web application

Having trouble converting dates in JavaScript? Check out this code snippet: $(document).ready(function () { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); ...

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

Having trouble showing images from block content using PortableText?

It's been quite a while now that I've been stuck on this issue. Despite being in a learning phase, I find myself unable to progress due to this specific problem. While links and text elements are functioning properly, I have encountered difficul ...

Codeigniter code to retrieve dynamic data in a select box

I am trying to implement a functionality where selecting an option from one dropdown will dynamically populate the options in another dropdown based on the selection. I believe I need to use an onchange function, but I'm unsure how to retrieve data fr ...

What methods can be used to restrict user input to numbers and letters only?

Is it possible to restrict the input in my text field username without using regex? I want users to only enter numbers and letters, with no white spaces or special characters. <div class="form-group has-feedback" ng-class="addUser.username.$valid ? &ap ...

Is there a way to enable scanned data to be automatically inputted into a field without manual entry?

I am in the process of creating a user-friendly Android app for virtual inventory management. I want the application to streamline data input by automatically populating text fields upon scanning, eliminating the need for users to manually click on each fi ...

"Having trouble subscribing? The first attempt doesn't seem to be working

I'm currently working on some TypeScript code that searches for the nearest point around a user in need of car assistance by checking a database. Once the nearest point is identified, the code retrieves the phone number associated with it and initiate ...

using reactjs to dynamically render elements based on the selected condition in a select box

Is there a way to dynamically change an element based on the selected value of a dropdown in React? I'm looking for help with rendering conditions. Here's a snippet of my code: <Col span={12}> <Form.Item label='Qu ...

Deliver the PDF generated document to Django Rest API

I have successfully created a PDF from an HTML file, Now, I am looking to automatically email the PDF as soon as it is generated. To achieve this, I need to send it to Django REST for backend processing. However, I am facing difficulties in figuring out h ...

There are a couple of issues here: specifically, the `this.myMethod` function is not recognized as a function, and the click event added by the `addEventListener` function

I am currently attempting to create a timer using vue.js, but I am encountering some issues with my methods section: methods: { saveRunningMethod() { var runningData = { duration: `${this.hour} : ${this.minute} : ${this.se ...

express-locale: locales property not functioning as intended

I've been experimenting with using express-locale (v1.0.5) as middleware in my express app to identify the locale based on the browser request. My goal is to compare the identified locale with a list of 'allowed' locales and use a default i ...

What is the best method for incorporating meta data, titles, and other information at dynamic pages using Node.js and Express?

I am currently exploring methods to efficiently pass data to the html head of my project. I require a custom title, meta description, and other elements for each page within my website. Upon initial thought, one method that comes to mind is passing the da ...