我有一个如下所示的树对象,我需要搜索它。我知道这里已经有一些关于此类主题的答案,但不幸的是,它们不符合我的结构。
const tree = {
"28": {
"label": "lorem"
"children": {
"188": {
"label": "ipsum"
"children": {
"482": {
"label": "fish"
"children": {
"185": {
"label": "dog"
},
"289": {
"label": "cat"
}
}
}
}
}
}
},
"33": {
"label": "water"
"children": {
"95": {
"label": "fire"
"children": {
"181": {
"label": "gas"
"children": {
"100": {
"label": "station"
}
}
}
"182": {
"label": ""
"children": {
"100": {
"label": "sushi"
}
}
}
}
}
}
}
}
例如,如果我要搜索“fish”,输出应该是这样的:
{
"28": {
"label": "lorem"
"children": {
"188": {
"label": "ipsum"
"children": {
"482": {
"label": "fish"
"children": {
"185": {
"label": "dog"
},
"289": {
"label": "cat"
}
}
}
}
}
}
}
}
如果我搜索“狗”:
{
"28": {
"label": "lorem"
"children": {
"188": {
"label": "ipsum"
"children": {
"482": {
"label": "fish"
"children": {
"185": {
"label": "dog"
}
}
}
}
}
}
}
}
我尝试使用这些先生的答案,但无法将它们适应命名对象:
使用递归函数在
children
属性中递归搜索。
请注意,我们在这里不使用扩展语法和函数方法,因为它会更慢。
const search = (obj, str) => {
for(const key in obj){
const item = obj[key];
if(item.label === str){
return {[key]: item };
}
if(item.children){
const found = search(item.children, str);
if(found){
return {[key]: Object.assign({}, item, {children: found})};
}
}
}
return null;
};
['fish', 'dog', 'dummy'].forEach(str => console.log(str, search(tree, str)));
<script>
const tree = {
"28": {
"label": "lorem",
"children": {
"188": {
"label": "ipsum",
"children": {
"482": {
"label": "fish",
"children": {
"185": {
"label": "dog"
},
"289": {
"label": "cat"
}
}
}
}
}
}
},
"33": {
"label": "water",
"children": {
"95": {
"label": "fire",
"children": {
"181": {
"label": "gas",
"children": {
"100": {
"label": "station"
}
}
},
"182": {
"label": "",
"children": {
"100": {
"label": "sushi"
}
}
}
}
}
}
}
}
</script>
要搜索树结构并保留其层次结构,您可以使用递归函数:
以下是解决方案的示例:
function filterTree(inputTree, searchTerm) {
let resultTree = {};
for (let key in inputTree) {
let node = inputTree[key];
// If the current label matches, it will return the entire subtree
if (node.label === searchTerm) {
resultTree[key] = node;
} else {
// Otherwise it will check the children
let childrenResult = node.children ? filterTree(node.children, searchTerm) : {};
// If any children matched, it will include this node in the result
// but only with those children that matched
if (Object.keys(childrenResult).length) {
resultTree[key] = { ...node, children: childrenResult };
}
}
}
return resultTree;
}
// Example of a usage
const searchTerm = 'fish';
const result = filterTree(tree, searchTerm);
console.log(result);
您可以将 searchTerm 替换为“狗”或您喜欢的任何其他生物,它应该可以工作。