搜索嵌套数据

Searching through nested data

我不知道这个搜索有什么问题function/s?我希望能够搜索鸟或蛇这个词。此外,最好忽略其中没有该文本的任何对象。我很困惑,因为这个人从不使用她的“动物”对象数组,而且我从来没有看到实际调用的 getEachItem?

example tutorial

const SlideData = [
  {
    id: 1,
    title: "Slide 0",
    layout: "standard",
    content: [
      {
        id: 1,
        type: "paragraph",
        text: "this has the word cat."
      },
      {
        id: 2,
        type: "space",
        height: "1em"
      },
      {
        id: 3,
        type: "paragraph",
        text: "this has the word snake."
      }
    ],
  },
  {
    id: 2,
    title: "Slide 1",
    layout: "standard",
    content: [
      {
        id: 1,
        type: "paragraph",
        text: "This has the word bird."
      },
      {
        id: 2,
        type: "space",
        height: "1em"
      },
      {
        id: 3,
        type: "paragraph",
        text: "This has the word bear."
      }
    ],
  }
];
export default SlideData;

import SlideData from "./SlideData";

const SearchResults = () => {
  const searchTerm = "bird";
  let result = [];

  function getEachItem(object) {
    object.forEach((item) => {
      searchItem(item);
    });
    let uniqueResults = [...new Set(result)];
    return uniqueResults.length;
  }
  function searchItem(item) {
    SlideData.forEach((key) => {
      if (typeof item[key] === "object") {
        searchItem(item[key]);
      }
      if (typeof item[key] === "string") {
        let searchAsRegEx = new RegExp(searchTerm, "gi");
        if (item[key].match(searchAsRegEx)) {
          result.push(item.id);
        }
      }
    });
  }

  return (
    <div>
      <h1>Results</h1>
      <p>{result}</p>
      <button type="submit" onClick={searchItem}>
        Search
      </button>
    </div>
  );
};
export default SearchResults;

教程通常是不费力的事情。这个作者似乎正在分享他们为另一个项目编写的东西的部分实现,并发布它以尝试获得反馈。他们没有编写具有完整搜索实现的应用程序。

在您的情况下,要搜索除“bird”以外的术语,您必须使 searchTerm 成为传递给函数的参数。您还必须设置表单和显示区域以放入结果。

重申一下,本教程仅为您提供完整应用程序的一部分。您必须自己设置其余部分。

看起来您正在对 searchItem 进行递归调用,但您从未指定 return 条件来弹出调用堆栈和 return 将控制流返回给原始调用者

function searchItem(item) {
    SlideData.forEach((key) => {
      if (typeof item[key] === "object") {
        /** return result of recursive call **/
        return searchItem(item[key]);
      }
      if (typeof item[key] === "string") {
        let searchAsRegEx = new RegExp(searchTerm, "gi");
        if (item[key].match(searchAsRegEx)) {
          result.push(item.id);
        }
      }
      /** return and pop call stack
       * since you pushed an item to the result array
       **/
      return;
    });
  }

最好让 searchItem 函数执行所有迭代和 return 数组结果,而不是递归地尝试将项目推送到全局数组。您正在将示波器与您现在的操作方式混合使用