首页 > 解决方案 > 使用键值获取对 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 级深度),但只是想我会指出它。

标签: javascriptjsonalgorithmrecursiontree

解决方案


这是一种可能性,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));


推荐阅读