如何将路径数组转换为JSON结构? [英] How to convert an array of paths into JSON structure?

查看:423
本文介绍了如何将路径数组转换为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.

这篇关于如何将路径数组转换为JSON结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆