[英]Return matching nodes in a nested tree: Javascript
I have an array of objects that is implemented as a tree with the follwing structure.我有一个对象数组,它们被实现为具有以下结构的树。 I am trying to implement a search functionality that basically searches the key inside these objects and return them by maintaining the relationship.我正在尝试实现一个搜索功能,该功能基本上搜索这些对象中的键并通过维护关系返回它们。
const arr = [
{
name: "internalcorp.com",
config: {
val1: false,
val2: false
},
children: [
{
name: "internalcorp.com.child1",
config: {
val1: true,
val2: true
},
children: [
{
name: "internalcorp.com.grandchild1",
config: {
val1: true,
val2: true
},
children: []
},
{
name: "internalcorp.com.grandchild2",
config: {
val1: false,
val2: true
},
children: []
}
]
},
{
name: "internalcorp.com.child2",
config: {
val1: true,
val2: false
},
children: []
}
]
},
{
name: "internalcorpwebsite.com",
children: [
{
name: "internalcorpwebsite.com.child1",
className: "level-1 leaf",
children: [],
val1: false,
val2: false
}
],
config: {
val1: false,
val2: false
}
}
];
Here I need to search the array based on key "name" recursively, and return that object maintaining the parent-child relationship.这里我需要递归地根据key“name”查找数组,返回维护父子关系的那个object。 THe search should be a contains
search搜索应该是contains
搜索
Code that I tried:我试过的代码:
function result(input) {
let res = arr.map((item) => {
if (item.name === input) return item;
});
return res;
}
console.log(result("website"));
Something like this, you can play with it here: Codepen Playground I've made the search to case insensitive and you can also search for multiple words, it should give you full tree and maintain parent-child relationship, try it out像这样的东西,你可以在这里玩: Codepen Playground我已经将搜索设置为不区分大小写,你也可以搜索多个单词,它应该给你完整的树并保持父子关系,试试看
const arr = [ { name: "internalcorp.com", config: { val1: false, val2: false }, children: [ { name: "internalcorp.com.child1", config: { val1: true, val2: true }, children: [ { name: "internalcorp.com.grandchild1", config: { val1: true, val2: true }, children: [] }, { name: "internalcorp.com.grandchild2", config: { val1: false, val2: true }, children: [] } ] }, { name: "internalcorp.com.child2", config: { val1: true, val2: false }, children: [] } ] }, { name: "internalcorpwebsite.com", children: [ { name: "internalcorpwebsite.com.child1", className: "level-1 leaf", children: [], val1: false, val2: false } ], config: { val1: false, val2: false } } ]; function result(input) { const v = input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const regex = new RegExp(v.trim().replace(" ", "|"), "i"); return arr.filter(function f(o) { let found = false; if (regex.test(o.name)) found = true; if (o.children) { const x = o.children.filter(f); if (x.length) { o.children = x; return true; } return found; } }); } console.log(result("website.com"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.