首页 > 解决方案 > 从数组内部过滤值

问题描述

我有一个过滤项目标签的解决方案。更新后书籍可以接收多个标签并添加标签数组:

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)是我无法过滤标签数组的地方,并且不知道如何使用扩展运算符或数组函数来过滤标签数组。有任何想法吗?

标签: javascriptarraysreactjs

解决方案


您正在将一个数组传递给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

推荐阅读