javascript - 搜索/过滤嵌套数组 Javascript/Lodash
问题描述
对于我的 React.js 项目,我想创建一个嵌套数组的搜索过滤器。用户将使用输入字段进行搜索。
var dataExample = [
{
type: "human", details: [
{id: 1, name: "Peter", description: "friendly, black-hair"},
{id: 5, name: "Susan", description: "blond"}
]
},
{
type: "animal", details: [
{id: 2, name: "Will", description: "lazy, cute"},
{id: 3, name: "Bonny", description: "beautiful"}
]
}
];
在我的搜索输入字段中,我想在“描述”中查找“名称”或其他内容。数组的数据结构应该保持不变。
我搜索“友好”或“彼得”时的输出应该是:
[
{
type: "human", details: [
{id: 1, name: "Peter", description: "friendly, black-hair"}
]
}
];
现在我尝试了这样的事情:
let myfilter = dataExample.filter((data) => {
data.details.filter((items) => {
return (items.type.indexOf("human") !== -1 || //input of user
items.description.indexOf("friendly"))
})
})
不幸的是,这不是它的工作方式。有谁能够帮我?Lodash 也没有问题。太感谢了。
解决方案
您可以使用array#reduce
witharray#filter
和 来检查您可以使用的单词string#incldues
。
const dataExample = [ { type: "human", details: [ {id: 1, name: "Peter", description: "friendly, black-hair"}, {id: 5, name: "Susan", description: "blond"} ] }, { type: "animal",details: [ {id: 2, name: "Will", description: "lazy, cute"}, {id: 3, name: "Bonny", description: "beautiful"} ] } ],
term = 'Peter',
result = dataExample.reduce((r, {type,details}) => {
let o = details.filter(({name,description}) => name.includes(term) || description.includes(term));
if(o && o.length)
r.push({type, details : [...o]});
return r;
},[]);
console.log(result);
推荐阅读
- r - 按 R 中的列获取汇总统计信息并放入表中
- javascript - 如何绕过firebase在响应时给出的数组中的随机ID?
- python-3.x - Flask-Bokeh 服务器:退出时释放内存
- mysql - 将 MySQL 表导出到 Microsoft SQL 服务器
- amazon-web-services - AWS批量限制单个主机上的容器数量
- vba - 复制和替换命名范围 Excel VBA
- android - 无法解析配置 ':app:debugRuntimeClasspath' 的所有依赖项
- sql - 基于层次结构的数据透视
- mdx - PowerPivot Query 上的 Filter() 太慢
- sql - 了解 VBA 以连接到 SQL