【发布时间】:2021-08-12 18:53:29
【问题描述】:
我不知道这个搜索功能有什么问题?我希望能够搜索“鸟”或“蛇”这个词。此外,最好忽略其中没有该文本的任何对象。我很困惑,因为这个人从不使用她的“动物”对象数组,而且我从来没有看到实际调用过 getEachItem?
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;
【问题讨论】:
标签: javascript arrays reactjs search nested