I was again working on a task for my hierarchical tree structure (see previous post here). This time I needed to find a specific object with a specific property value.
So here again my nested array:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | const aTreeData = [ { "NodeId" : 1 , "HierarchyLevel" : 1 , "type" : "folder" , "nodes" : [ { "NodeId" : 2 , "HierarchyLevel" : 2 , "type" : "folder" , "nodes" : [ { "NodeId" : 3 , "HierarchyLevel" : 3 , "type" : "category" } ] } , { "NodeId" : 4 , "HierarchyLevel" : 2 , "type" : "category" , "nodes" : [ { "NodeId" : 5 , "HierarchyLevel" : 3 , "type" : "file" } ] } ] } , { "NodeId" : 6 , "HierarchyLevel" : 1 , "type" : "folder" , "nodes" : [ { "NodeId" : 7 , "HierarchyLevel" : 2 , "type" : "category" } ] } ] |
I needed a function that was able to find any object by providing only the NodeId value. Fortunately I stumbled accross some excellent code snippet by Scott Sauyet which is exactly doing what I needed:
I just had to change the properties to match my objects and it was working!
01 02 03 04 05 06 07 08 09 10 11 | const findNodeInTreeData = ( aTreeData , nodeId ) = > { const deepFind = pred = > ( [ x , . . . xs ] = [ ] ) = > x & & ( pred ( x ) ? x : deepFind ( pred ) ( x . nodes ) | | deepFind ( pred ) ( xs ) ) const findByNodeId = id = > obj = > deepFind ( o = > o . NodeId = = id ) ( [ obj ] ) return findByNodeId ( nodeId ) ( aTreeData [ 0 ] ) } console . log ( findNodeInTreeData ( aTreeData , 5 ) ) |