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]];
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)