Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to arbitrarily (deep) nested node inside JSON/JS object using value of key

I have been looking all night on SO with lots of similar issues but none that directly solves my problem at the moment. So please have a look below.

I have an object of the form:

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": [

     ]
   }]
 }
]

Basically, children contains an array of the same structure nodes.

If I wish to get a reference to the node that contains, say, id:783, I would intuitively use recursion but I'm at a loss as to how I would ensure that it covers the entire tree recursively until it finds and returns the exact node that I want so that I could append more children to the found node.

Admittedly, despite coming from a CS background, my knowledge of recursion is rather rusty.

This is what I've tried in my jsfiddle: https://jsfiddle.net/hanktrizz/surmf7dq/4/

Note that the data tree could be arbitrarily deep (though I don't expect it to go past 8 or 9 levels of depth) but just thought I'd point it out.

like image 712
Han K Avatar asked Jan 30 '26 06:01

Han K


1 Answers

Here's one possibility, using a for loop in a recursive function:

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));
like image 111
CertainPerformance Avatar answered Feb 01 '26 21:02

CertainPerformance