对于我的 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"}
]
}
];
在我的搜索输入字段中,我想查找“名称”或“描述”中的内容。 数组的数据结构应该保持不变。
当我搜索“friendly”或“Peter”时,输出应该是:
[
{
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
与 array#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);
关于javascript - 搜索/过滤嵌套数组 Javascript/Lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248036/