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

如何将路径数组转换为JSON结构?,第1张

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

const 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”
];


const output = {};let current;for (const path of data) {    current = output;    for (const segment of path.split('/')) {        if (segment !== '') { if (!(segment in current)) {     current[segment] = {}; } current = current[segment];        }    }}console.log(output);

您的解决方案很接近,只是没有

current
正确重置变量。用这个:

current = output;

代替这个:

current = output[path[0]];


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5615196.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存