Search code examples
javascriptvue.jscomputed-properties

vue filtersearch an array of object inside an array of object


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


Solution

  • 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())
          )
        )
      }
    }