如何根据用户输入过滤对象内的数组并移除无匹配项的键
问题解决:根据搜索输入过滤对象数组并清理空键
需求说明
现有如下数据对象,需要根据用户输入的searchInput过滤数组值:
- 过滤规则:仅保留数组中包含搜索关键词的元素
- 若过滤后对应键的数组为空,则移除该键
const data = { "text-a": ["Text-1", "Text-2", "Example-3", "Text-4"], "text-b": ["Example-1", "Example-2", "Other-Example-3", "Text-1b"] } // 该对象应仅保留与searchInput匹配的数据 var filteredData = {} // 该值会随用户文本输入变化 var searchInput = "tex"
原代码问题分析
原实现使用forEach遍历键并赋值,但forEach本身没有返回值,直接把它的结果赋值给filteredData会得到undefined。另外,原代码没有处理过滤后数组为空的情况,会留下空数组的键。
原非工作代码:
filteredData = Object.keys(data).forEach((key) => ( filteredData[key] = data[key].filter((x) => (x.includes(searchInput))) ))
正确实现方案
方案一:使用reduce一次性完成过滤与清理
filteredData = Object.keys(data).reduce((acc, key) => { // 过滤当前数组中包含搜索关键词的元素(需忽略大小写可改成x.toLowerCase().includes(searchInput.toLowerCase())) const filteredArr = data[key].filter(x => x.includes(searchInput)); // 仅当过滤后的数组非空时,才添加到结果对象中 if (filteredArr.length > 0) { acc[key] = filteredArr; } return acc; }, {});
方案二:先遍历赋值,再清理空数组的键
如果更习惯forEach的写法,也可以先完成过滤赋值,再删除空数组对应的键:
// 先遍历过滤并赋值 Object.keys(data).forEach(key => { filteredData[key] = data[key].filter(x => x.includes(searchInput)); }); // 遍历结果对象,删除空数组的键 Object.keys(filteredData).forEach(key => { if (filteredData[key].length === 0) { delete filteredData[key]; } });
效果验证
当searchInput = "tex"时,最终filteredData的结果为:
{ "text-a": ["Text-1", "Text-2", "Text-4"], "text-b": ["Text-1b"] }
内容的提问来源于stack exchange,提问作者fm84
相关产品推荐
相关产品推荐

