vue filter 在对象数组中搜索对象数组
vue filtersearch an array of object inside an array of object
我有一个 JSON 格式的数据,我从 api 调用中检索到它,它的结构如下所示。
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' }]
},
....
]
现在,我有一个名为 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())
: ''
})
}
}
}
这在我搜索名称时效果很好,但是当我搜索学校名称时,我如何才能做到同样的效果
您需要过滤器中的另一个过滤器。
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;
}
我对 filterSearch()
做了一些改进,还实现了 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())
)
)
}
}
我有一个 JSON 格式的数据,我从 api 调用中检索到它,它的结构如下所示。
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' }]
},
....
]
现在,我有一个名为 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())
: ''
})
}
}
}
这在我搜索名称时效果很好,但是当我搜索学校名称时,我如何才能做到同样的效果
您需要过滤器中的另一个过滤器。
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;
}
我对 filterSearch()
做了一些改进,还实现了 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())
)
)
}
}