如何将路径数组转换为JSON结构?

问题描述:

我发现了一个问题:如何将文件路径转换为树视图? ,但我不确定如何在JavaScript中获得所需的结果:

I found the question How to convert a file path into treeview?, but I'm not sure how to get the desired result in JavaScript:

我正在尝试将路径数组转换为JSON树:

I'm trying to turn an array of paths into a JSON tree:

https://jsfiddle.net/tfkdagzv/ 16 /

但我的路径被覆盖了。

我正试图拿东西像这样:

I'm trying to take something like this:

[
    '/org/openbmc/path1', 
    '/org/openbmc/path2', 
    ...
]

...并转向它进入......

... and turn it into...

output = {
   org: {
     openbmc: {
       path1: {},
       path2: {}
     }
   }
}

我确定这很简单,但我遗漏了一些东西。

I'm sure this is pretty easy, but I'm missing something.

这是我写的解决方案:

var data = [
 "/org/openbmc/examples/path0/PythonObj",
 "/org/openbmc/UserManager/Group",
 "/org/openbmc/HostIpmi/1",
 "/org/openbmc/HostServices",
 "/org/openbmc/UserManager/Users",
 "/org/openbmc/records/events",
 "/org/openbmc/examples/path1/SDBusObj",
 "/org/openbmc/UserManager/User",
 "/org/openbmc/examples/path0/SDBusObj",
 "/org/openbmc/examples/path1/PythonObj",
 "/org/openbmc/UserManager/Groups",
 "/org/openbmc/NetworkManager/Interface"
];

var output = {};
var current;

for(var a=0; a<data.length; a++) {
  var s = data[a].split('/');
  current = output;
  for(var i=0; i<s.length; i++) {
    if(s[i] != '') {
      if(current[s[i]] == null) current[s[i]] = {};
      current = current[s[i]];
    }
  }
}

console.log(output);

它将完成您需要的所有操作,并且非常紧凑。但是,对于解决方案中的问题,它与您如何管理当前有关。具体来说,你有这个:

It will do everything you need it to, and is compact. But, for the problem in your solution, it has to do with how you are managing current. Specifically, you had this:

current = output[path[0]];

而不是:

current = output;

这意味着初始化输出的代码 ,每次都会运行,因为 path [0] 在您的数据中始终是'',和输出[''] 尚不存在,因此输出将始终被重置/覆盖。

which meant that the code to initialize output, would run every time, because path[0] is, in your data, always going to be '', and output[''] doesn't yet exist, so output would always be reset/overwritten.