我正在使用文本搜索某些数据。有些数据是嵌套的,而另一部分则不是。
我也把它放在codeSandbox上 - https://codesandbox.io/s/Q0w16jLP0
功能:
function filterTypes(items, search) {
return items.filter(items => {
const nestedName = items.typechild.map(x => x.name.toLowerCase());
const name = items.name.toLowerCase();
return search.every(x => {
return name.includes(x) || nestedName.some(v => v.includes(x));
});
});
}
数据结构:
{
"name": "Food",
"typechild": [{
"name": "Fruit", "id":12,
}, {
"name": "Vegetable", "id":13,
}]
}
现在如何运作:
Food
的所有子项。期望的结果:
如果过滤器的值为Fruit
,则应返回...
Food
作为标题Fruit
低于该标题所需的数据结构
{
"name": "Food",
"typechild": [{
"name": "Fruit", "id":12,
}]
}
答案 0 :(得分:0)
我会使用递归方法:
function check(el,name){
if(el.name.includes(name)){
return [el];
}
if(el.typechild && el.typechild.find){
var child=el.typechild.find(function(child){
return check(child,name);
});
}
if(child){
child=check(child,name);
child.unshift(el);
return child;
}
return false;
}
它会返回
[Food Object, Fruit Object]
答案 1 :(得分:0)
改变原始数据的解决方案。
var data = [{ name: "Food", typechild: [{ name: "Fruit", level: 2, color: "#fff" }, { name: "Vegetable", level: 2, color: "#fff" }] }, { name: "Entertainment", typechild: [{ name: "Book", level: 2, color: "#fff" }, { name: "Movie", level: 2, color: "#fff" }, { name: "Bar", level: 3, color: "#fff" }] }, { name: "Misc", typechild: [{ name: "Foo", level: 2, color: "#fff" }] }],
search = 'Fruit',
index = data.length,
temp;
while (index--) {
temp = data[index].typechild.filter(o => o.name === search);
if (temp.length) {
data[index].typechild = temp;
} else {
data.splice(index, 1);
}
}
console.log(data);

.as-console-wrapper { max-height: 100% !important; top: 0; }