如何过滤嵌套数组中的字符串?

时间:2019-10-27 20:57:23

标签: javascript reactjs

我正在尝试实现一个搜索功能,该功能返回在指定数组中具有搜索词的find。假设某个集合具有[aa,ab,aaa],并且搜索词为“ a”。在这种情况下,返回要显示的对象。因为数组中的至少一个字符串具有'a'。

dataStructure

[
  {
   name:'aa',
   searchWords:['aa','ab','bc'] <- I want to use this array for search
  },
  {
   name:'bb',
   searchWords:['bb','bc','de'] <- I want to use this array for search
  },
...
]

我尝试通过使用include(),filter(),indexOf()解决此问题。但是,当搜索字词完全匹配时,它仍然不返回任何内容或返回数据。 如何修复代码以实现目标? 预先谢谢你!

这部分效果很好

let filterStudents = students;
if (searchName.length > 0 && searchTag.length === 0) {
  filterStudents = students.filter((student) => {
    if (
      student.firstName.toLowerCase().includes(searchName.toLowerCase())
      || student.lastName.toLowerCase().includes(searchName.toLowerCase())
    ) {
      return true;
    }
    return false;
  });

此部分出现问题

} else if (searchName.length === 0 && searchTag.length > 0) {
  filterStudents = students.filter(
    (student) => {
      console.log(student.tags);
      student.tags.filter((tag) => {
        console.log(tag);
        tag.indexOf(searchTag) > -1;
      });
    },
  );
} else if (searchName.length > 0 && searchTag.length > 0) {
} else {
  console.log('both');
}

2 个答案:

答案 0 :(得分:0)

您不会从return回调中filter

作为旁注,还有String#includes

filterStudents = students.filter(student =>
  student.tags.some((tag) => tag.includes(searchTag))
);

答案 1 :(得分:0)

如果仅在填写了相应的@ManyToOne @JoinColumn(name="teachers") @JsonIgnoreProperties("course") Teacher teach; searchTag后才要搜索匹配项,请在searchName回调内使用条件运算符检查是否应进行过滤器测试退出:

filter
const students = [
  {
   name:'aa',
   searchWords:['aa','ab','bc']
  },
  {
   name:'bb',
   searchWords:['bb','bc','de']
  },
];
const doFilter = () => {
  const [searchName, searchTag] = [...document.querySelectorAll('input')]
    .map(input => input.value.toLowerCase());
  const filtered = students.filter(({ name, searchWords }) => (
    (searchName ? name.toLowerCase().includes(searchName) : true) &&
    (searchTag ? searchWords.some(word => word.toLowerCase().includes(searchTag)) : true)
  ));
  code.textContent = JSON.stringify(filtered);
};

window.addEventListener('change', doFilter);