TransWikia.com

vue filtersearch an array of object inside an array of object

Stack Overflow Asked by stackved12 on December 18, 2020

I have a JSON formatted data that I retrieve from an api call, its structure looks 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' }] 
         },
         ....
       ]

now, in I have a computed property called 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()) 

                   : ''
                })
            }
    }
}

This works well when I search the name, but how do I make it work to do the same when I search the school name

2 Answers

I made some improvement to filterSearch() and also implemented 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())
      )
    )
  }
}

Correct answer by DevMaster on December 18, 2020

You need another filter in filter.

filterSearch() {
    if(this.search != '') {
        return this.teachers_list.filter( hero => {
            hero.name.toLowerCase().includes(this.search.toLowerCase()) ||
            hero.school.filter(x => x.name.toLowerCase().includes(this.search.toLowerCase()).length > 0
        })
    }
    return this.teachers_list;
}

Answered by Bülent Akgül on December 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP