首页 > 解决方案 > 在 React 中使用 regExp 查询嵌套数据

问题描述

在这里可能更容易理解我的问题: 我的搜索栏示例

我遇到的问题是如何搜索所有文本属性,而不仅仅是内容数组中的第一个。上面的 codeSandbox 可能更有帮助。此外,如果不存在文本属性(或搜索词),我只想不显示任何内容或显示消息。我简化了数据,但通常 text 属性中有很多文本。尝试在沙盒中搜索鸟,然后尝试熊。熊没有出现。我认为我的过滤方法或我的映射有问题?

const SlideData = [
  {
    index: 0,
    title: "Slide 0",
    layout: "standard",
    content: [
      {
        type: "paragraph",
        text: "this has the word cat.",
      },
      {
        type: "space",
        height: "1em",
      },
      {
        type: "paragraph",
        text: "this has the word dog.",
      },
    ],
    image: image1,
    width: imageSize,
  },
  {
    index: 1,
    title: "Slide 1",
    layout: "standard",
    content: [
      {
        type: "paragraph",
        text: "this has the word bird",
      },
      {
        type: "space",
        height: "1em",
      },
      {
        type: "paragraph",
        text: "this has the word bear",
      },
    ],
    image: image2,
    width: imageSize,
  },
//SPLIT THE SEARCH TERM AND STYLE THE PIECES//
  const splitResult = (result) =>
    result.split(new RegExp(`(${searchTerm})`, `gi`)).map((piece, index) => {
      return (
        <span
          key={index}
          style={{
            background: piece.toLowerCase() === searchTerm.toLocaleLowerCase() ? "GOLD" : "TRANSPARENT",
            color: piece.toLowerCase() === searchTerm.toLocaleLowerCase() ? "BLACK" : "WHITE"}}
        >
          {piece}
        </span>
      );
    });
 const filterData = () => {
    return SlideData.filter((item) => {
      if (searchTerm === "") {
      } else {
        //concat the text properties into variable
        let searchText = item.title + item.content[0].text;
        //if the variable contains the search term value
        if (searchText.toLowerCase().includes(searchTerm.toLowerCase())) {
          //return those items
          return item;
        }
      }
    }).map((item) => (
      <div style={{ padding: "0.5rem 0rem" }} key={item.index}>
        <h3>{splitResult(item.title)}</h3> 

        //WORKS BUT NOT DYNAMIC ???//
        <li>{splitResult(item.content[0].text)}</li> 
        <li>{splitResult(item.content[2].text)}
        <div className={styles.searchLink}>
          <a
            onClick={() => {
              context.setCurrentSlide(item.index - 1);
              setSearchTerm("");
              hideResults();
              clearInput();
              toggleSearch();
            }}
          >
            Go To This Slide {item.index}
          </a>
        </div>
      </div>
    ));
  };

标签: javascriptreactjssearchmethodsregexp-substr

解决方案


推荐阅读