我有一个可以过滤项目标签的解决方案。更新以便书籍可以接收多个标签并添加标签数组:
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)
是我无法过滤标签数组,也不知道如何使用 maybe spread 运算符或数组函数来过滤标签数组。有什么想法吗?
最佳答案
我认为它可以与数组函数 some
一起使用
selectedTags.length > 0 ? selectedTags.some(st => item.tag.includes(st)) : true
有了这个,至少一个选定的标签应该与图书标签列表相匹配,并且它将被显示。
关于javascript - 从数组内部过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614781/