1

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

asked Oct 26, 2020 at 12:02

2 Answers 2

2

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 Oct 26, 2020 at 12:13

Comments

1

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())
 )
 )
 }
}
answered Oct 26, 2020 at 12:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.