我试图寻找一个嵌套的JSON阵列具有匹配名称的一个对象。我的数据结构如下所示:
[
{
"type": "directory",
"name": "/home/user/test-tree",
"contents": [
{
"type": "directory",
"name": "my-folder",
"contents": [
{
"type": "directory",
"name": "nested-folder",
"contents": []
}
]
},
{
"type": "directory",
"name": "node_modules",
"contents": [
{
"type": "directory",
"name": "gunzip-file",
"contents": []
}
]
}
]
}
]
因此,在这个例子中,我可以寻找一个名为“node_modules”目录,它应该返回整个对象,包括它的内容。这仅仅是一个样品,我的实际数据集可能是相当大 - 树可以代表对例如文件系统中的所有目录。
这是我现在使用的代码 - 它似乎在这个例子中工作,但它似乎并没有与大型数据集的正常工作,我实在看不出有什么毛病,所以如果有人能发现任何东西我倒是欣赏它。
function treeSearch(array, dirName) {
for (let i = 0; i < array.length; i++) {
if (array[i].name === dirName) {
return array[i]
}
else if (array[i].contents) {
if (array[i].contents.length > 0) {
return treeSearch(array[i].contents, dirName)
}
}
}
}
有没有在你的代码中的错误,在你只是递归的三个单支的那一刻,你不是递归在整个数据结构,事实上,如果你想搜索“node_modules”你的代码返回undefined 。
尝试这个小小的修改应用到你的代码
const data = [
{
"type": "directory",
"name": "/home/user/test-tree",
"contents": [
{
"type": "directory",
"name": "my-folder",
"contents": [
{
"type": "directory",
"name": "nested-folder",
"contents": []
}
]
},
{
"type": "directory",
"name": "node_modules",
"contents": [
{
"type": "directory",
"name": "gunzip-file",
"contents": []
}
]
}
]
}
];
function treeSearch(array, dirName) {
for (let i = 0; i < array.length; i++) {
if (array[i].name === dirName) {
return array[i];
}
else if (array[i].contents && array[i].contents.length) {
const result = treeSearch(array[i].contents, dirName);
// return the result only if it's actually found otherwise keep looping
if(result) return result;
}
}
}
console.log(treeSearch(data, "node_modules"));
你可以采取它迭代与可能性阵列短暂circiut,如果值找到一个递归函数。
function find(array, value) {
var result;
array.some(o => result = o.name === value && o || find(o.contents, value));
return result || undefined;
}
var data = [{ type: "directory", name: "/home/user/test-tree", contents: [{ type: "directory", name: "my-folder", contents: [{ type: "directory", name: "nested-folder", contents: [] }] }, { type: "directory", name: "node_modules", contents: [{ type: "directory", name: "gunzip-file", contents: [] }] }] }]
console.log(find(data, "node_modules"));
.as-console-wrapper { max-height: 100% !important; top: 0; }