javascript - 在 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>
));
};
解决方案
推荐阅读
- node.js - Steam API 禁止交易报价 403
- pivot - 在 Teradata 中将行转换为列
- python - 如何在 Django 中使用多对多字段进行 GROUP BY 查询
- python - 在 HTML 按钮中使用 url_for 传递参数
- extjs - 文本字段EXTJS中的问题箭头键导航
- python - 将年和月组合为整数或对象,同时忽略 nan
- angular - Angular-AG Grid Enterprise:agSetColumnFilter applyMiniFilterWhileTyping
- r - 向图表添加“噪声”
- python - 在 python Pandas 中加入表(如基于两列值相似性的 Vlookup)
- python - 检查熊猫系列中的整数