Get an object with a given attribute from a deep hierarchy

Suppose I have a hierarchy of objects that can have children. All objects have a unique id . I need to get an object from anywhere in this hierarchy if only id is given. For example, a hierarchy might look like this:

  var hierarchy = [
   {id: 1, children: [
     {id: 7},
     {id: 8}
   ]},
   {id: 2},
   {id: 3, children: [
     {id: 9},
     {id: 10, children: [
       {id: 11},
       {id: 12},
       {id: 13}
     ]}
   ]},
   {id: 4},
   {id: 5},
   {id: 6, children: [
     {id: 14}
   ]}
 ];

And the function call will look something like this:

  retrieveObjectById (10, hierarchy);
 // => {id: 10, children: [...]}

I tried writing a function using Array.filter, which would recursively call child elements in a collision, but would also return its ancestors.

+4
source share
1 answer

The idea to solve these problems consists, as a rule, in using such a recursive function:

 function deepFind(obj, id) { if (obj.id==id) return obj; if (obj.children) { for (var i=0; i<obj.children.length; i++) { var o = deepFind(obj.children[i], id); if (o) return o; } } } 

Since your root level object does not have the same structure, you can either loop around hierarchy or make it look like:

 var myObject = deepFind({children:hierarchy}, 10); 

Demonstration

+3
source

Source: https://habr.com/ru/post/1480146/


All Articles