javascript - 从数组内部过滤值
问题描述
我有一个过滤项目标签的解决方案。更新后书籍可以接收多个标签并添加标签数组:
const bookListBefore = [
{ id: 1, tag: 'Fysik' },
{ id: 2, tag: 'Marketing' },
{ id: 3, tag: '' },
];
const bookListNow = [
{ id: 1, tag: ['Fysik', 'Matematik'] },
{ id: 2, tag: ['Analytics', 'Marketing', 'Data'] },
{ id: 3, tag: [''] },
];
现在我正在努力寻找一种解决方案来过滤那些具有特定标签的项目。在使用单个标签之前,我可以执行过滤器并可以使用此解决方案显示带有特定标签的项目:
const filteredList = bookList
.filter(item => (item.title.toLowerCase().includes(searchTextHome)
|| item.author.toLowerCase().includes(searchTextHome))
&& (selectedTags.length > 0 ? selectedTags.includes(item.tag) : true));
<section className={stylesSCSS.bookContainer}>
{filteredList.length === 0 ? emptyPlaceholder()
: filteredList.map(item => (
<BookItem
cover={item.cover}
item={item}
userTagData={userTagData}
onTagSelected={onTagSelected}
/>
))
}
</section>
“搜索”过滤 bookList 的第一部分是关于输入搜索字段,但第二部分(selectedTags.length > 0 ? selectedTags.includes(item.tag) : true)
是我无法过滤标签数组的地方,并且不知道如何使用扩展运算符或数组函数来过滤标签数组。有任何想法吗?
解决方案
您正在将一个数组传递给includes
. includes
接受两个参数,第一个是要检查的值,第二个是数组中的位置(可选)
[1,2,3].includes(1) //true
[1,2,3].includes(1,3) //false
您需要tag
一次检查每个元素
const { tag } = book
for(let item of tag){
if(list.includes(item)) return true
}
return false
您的代码应如下所示
const filteredList = bookList.filter(item =>
(item.title.toLowerCase().includes(searchTextHome)
|| item.author.toLowerCase().includes(searchTextHome))
const result = selectedTags.length > 0 ? filteredList.filter(x =>{
const { tag } = x
for(let item of tag) {
if(selectedTags.includes(item)) return true
}
return false
}) : filteredList
推荐阅读
- javascript - 浏览器同步不工作我如何修复和测试以确保它工作?
- go - 去通用频道类型
- g++ - Linux下如何在Conda上安装g++?
- swift - 检查 Firebase 实时数据库中的现有值
- firebase - Flutter Streambuilder 流不一致的 FirebaseFirestore 快照数据
- r - 如果列中的值包含字符串列表中的元素,则返回 True 或 False R
- c# - 如何对 c#reactivex.io 进行单元测试
- spring-boot - Primefaces v8.0 验证码不适用于 Spring Boot 2.0.6
- r - 使用 R 删除所有点,但首先在字符串中
- android - Android / IOS / WEB框架加载一个html页面。添加缓存