0

I have a list of paths like this :

var paths = [

"/org/openbmc/UserManager/Group",
"/org/openbmc/records/events",
"/org/openbmc/HostServices",
"/org/openbmc/UserManager/Users",
"/org/openbmc/records/transactions",
"/org/openbmc/UserManager/Groups",

];

And I would like to transform it into a JSON to have this :

var list = {
 "name": "org",
 "path": "/org",
 "children": [
  {
   "name": "openbmc",
   "path": "/org/openbmc",
   "children": [
    {
     "name": "UserManager",
     "path": "/org/openbmc/UserManager",
     "children": [
      {
       "name": "Group",
       "path": "/org/openbmc/UserManager/Group"
      },
      {
       "name": "Users",
       "path": "/org/openbmc/UserManager/users"
      },
      {
       "name": "Groups",
       "path": "/org/openbmc/UserManager/Groups"
      }
     ]
    },
    {
     "name": "records",
     "path": "/org/openbmc/records",
     "children": [
      {
       "name": "events",
       "path": "/org/openbmc/records/events"
      },
      {
       "name": "transactions",
       "path": "/org/openbmc/records/transactions"
      }
     ]
    }
   ]
  }
 ]
}

Seems many node.js lib can do this, but I cant find in Javascript the exact same structure. Do you have an idea ?

cineciine
  • 1
  • 1
  • Your proposed json is invalid. what are the braces doing after each path – James Jun 27 '17 at 15:08
  • Yes, we fixed this problem. – cineciine Jun 28 '17 at 09:07
  • Similar: https://stackoverflow.com/questions/18017869/build-tree-array-from-flat-array-in-javascript – James Jun 28 '17 at 15:12
  • @James yes indeed the post you linked us might be smiliar, but actually our input is different, and the hierarchy depends of the paths. We have a tab as input and we don't have id attributes, is it realisable ? – cineciine Jun 29 '17 at 09:37
  • The post shows a few techniques for building a tree structure. You're right about the inputs being different but the base methods are the same (iterate something, in your case the path of each item in the array, split the path, create a node at each level, if the path contains more parts recursively create a node connected to the one you just made at each additional level) – James Jun 29 '17 at 13:05

0 Answers0