javascript - 使用键值获取对 JSON/JS 对象内任意(深)嵌套节点的引用
问题描述
我整晚都在寻找很多类似的问题,但目前没有一个能直接解决我的问题。所以请看下面。
我有一个形式的对象:
let data = [{
"id": 777,
"name": "Level 1_section_1",
"children": [{
"id": 778,
"name": "Level 2a",
"children": [
]
},
{
"id": 783,
"name": "Level 2b",
"children": [
]
}
]
},
{
"id": 786,
"name": "Level 1_section_2",
"children": [{
"id": 781,
"name": "Level 2c",
"children": [
]
}]
}
]
基本上,children 包含一个相同结构节点的数组。
如果我希望获得对包含 的节点的引用id:783
,我会直观地使用递归,但我不知道如何确保它递归地覆盖整个树,直到它找到并返回确切的节点我想要这样我可以将更多的孩子附加到找到的节点。
诚然,尽管我来自 CS 背景,但我对递归的了解相当生疏。
这是我在我的 jsfiddle 中尝试过的: https ://jsfiddle.net/hanktrizz/surmf7dq/4/
请注意,data
树可以任意深(尽管我不希望它超过 8 或 9 级深度),但只是想我会指出它。
解决方案
这是一种可能性,for
在递归函数中使用循环:
let data=[{id:777,name:"Level 1_section_1",children:[{id:778,name:"Level 2a",children:[]},{id:783,name:"Level 2b",children:[]}]},{id:786,name:"Level 1_section_2",children:[{id:781,name:"Level 2c",children:[]}]}];
const findNode = (arr, idToFind) => {
for (const item of arr) {
if (item.id === idToFind) {
return item;
}
const possibleResult = findNode(item.children, idToFind);
if (possibleResult) {
return possibleResult;
}
}
};
console.log(findNode(data, 778));
推荐阅读
- sql - SQL 不使用连接查找所有销售订单
- python - 如何智能地从单个 .csv 文件导入多个 pandas 数据帧?
- android - [Flutter] url_launcher 包导致的错误(找不到路径)
- arduino - 在 Arduino ESP8266 中将多个中断附加到单个 ISR 函数
- linux - 如何在 Linux 中拆分文件名中的数字?
- text - SwiftUI:“审查”/标记文本效果
- php - Yii2中如何将不同文件中的每个动作分开
- matlab - Matlab将一组图像更改为2D灰度但出现错误
- sql - 为什么 SUM 值在 postgresql 查询中是错误的?
- python - 处理传播错误