javascript - 在JS中递归搜索嵌套数组
问题描述
我正在尝试在嵌套的 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)
}
}
}
}
解决方案
如果找到值,您可以采用递归函数迭代数组,并可能出现短路。
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; }
推荐阅读
- kubernetes - 如何为在云中运行的应用程序配置 db vault?
- ios - 如何在 iOS Release 模式下查看 React Native 的 console.log?
- html - 超级菜单(仅限 CSS)悬停无法正常工作
- api - 第 3 方(条带化)元数据最佳实践?
- java - 一次构建所有 Maven 依赖项
- python - pyrogram - 用于获取实时位置更新的电报 API
- oracle - ora2pg 排除指令的问题
- delphi - 如何将 HTML 格式的文本作为 HTML 复制到 Firemonkey 中的剪贴板
- java - 红黑树 - 如何处理插入的第一个项目
- javascript - 如何在反应传单中选择一个区域