React中实现搜索栏过滤大型嵌套JSON的标题内容
解决React中嵌套JSON分类文章的过滤问题
核心思路是保留原对象结构,遍历每个分类并过滤其中的文章,最后重组为同结构的新对象。你用Object.entries的思路是对的,只需配合reduce完成对象重组即可:
示例代码
假设你的原始文章数据结构如下:
const articlesData = { HOME: [ { title: "国内头条", link: "/home-1" }, { title: "全球热点", link: "/home-2" } ], WORLD: [ { title: "国际政治动态", link: "/world-1" }, { title: "国内科技突破", link: "/world-2" } ], UK: [ { title: "英国天气预警", link: "/uk-1" }, { title: "全球经济走势", link: "/uk-2" } ] };
实现过滤函数:
const filterArticles = (rawData, searchKeyword) => { const lowerKeyword = searchKeyword.toLowerCase().trim(); // 遍历原对象的分类键值对,重组为新对象 return Object.entries(rawData).reduce((result, [category, articles]) => { // 过滤当前分类下标题包含搜索词的文章 const matchedArticles = articles.filter(article => article.title.toLowerCase().includes(lowerKeyword) ); // 可选:如果想保留空分类(过滤后无匹配文章的分类),直接赋值即可 // result[category] = matchedArticles; // 只保留有匹配文章的分类(按需选择) if (matchedArticles.length > 0) { result[category] = matchedArticles; } return result; }, {}); // 初始值为空对象,保证返回结构和原数据一致 };
React组件中使用
结合useState管理搜索词,实时生成过滤结果:
import { useState } from 'react'; function SearchableArticles() { const [searchTerm, setSearchTerm] = useState(''); const filteredArticles = filterArticles(articlesData, searchTerm); return ( <div> <input type="text" placeholder="搜索文章标题..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> {/* 渲染过滤后的文章,结构和原数据一致,直接按分类遍历即可 */} {Object.keys(filteredArticles).map(category => ( <div key={category}> <h3>{category}</h3> <ul> {filteredArticles[category].map(article => ( <li key={article.link}> <a href={article.link}>{article.title}</a> </li> ))} </ul> </div> ))} </div> ); }
关键说明
Object.entries(rawData):把原对象拆分为[分类名称, 文章数组]的二维数组,方便同时获取分类键和对应文章列表reduce:遍历过程中逐步构建和原结构一致的新对象,避免返回数组- 过滤逻辑做了大小写不敏感处理,同时去除了搜索词前后空格,提升用户体验
内容的提问来源于stack exchange,提问作者user21449946
相关产品推荐
相关产品推荐

