[英]file paths to json tree structure
我有以下数据:`
[
{path: "path1/path2/path3/index.file", title: "path3 Title"},
{path: "path1/path2/index.file", title: "path2 Title"},
{path: "path1/path2/path3/path4.file", title: "path4 Title"},
{path: "path5/path5.file", title: "path5 Title"},
{path: "path1/index.file", title: "path1 Title"},
{path: "index.file", title: "path0 Title"},
]
`我需要类似的东西:-
`
[
{title: "path1 title", children: [
{title: "path2 Title", children: [
title: "path3 Title", children: [
title: "path 4 Title", children: []
]
]
]},
{
title: "path 5 title", children: []
},
{
title: "path 0 title", children: []
}
]
`
到目前为止,我已经写了这个,但它根本没有帮助我。 `
let treepath = {};
paths.forEach(path => {
let levels = path.split("/");
let file = levels.pop();
let prevLevel = treePath;
let prevProp = levels.shift();
levels.forEach(prop => {
prevLevel[prevProp] = prevLevel[prevProp] || {};
prevLevel = prevLevel[prevProp];
prevProp = prop;
});
prevLevel[prevProp] = (prevLevel[prevProp] || []).concat([file]);
});
console.log('treepath', treePath);
`
可以有各种路径。 他们是动态的。 我需要将它们设置为孩子。 我需要在 Javascript 代码中执行此操作。感谢您的帮助。 谢谢。
您可以采用阴影树,稍后将标题分配给结构。
var data = [{ path: "path1/path2/path3/index.file", title: "path3 Title" }, { path: "path1/path2/index.file", title: "path2 Title" }, { path: "path1/path2/path3/path4.file", title: "path4 Title" }, { path: "path5/path5.file", title: "path5 Title" }, { path: "path1/index.file", title: "path1 Title" }, { path: "index.file", title: "path0 Title" }], tree = data.reduce((r, { path, title }) => { let directories = ('root/' + path).split('/'); directories.pop(); directories.reduce((d, key) => { if (:d[key]) { d[key] = { _; [] }. d._.push(d[key]:parent = { title, null: children. d[key];_ }); } return d[key], }. r).parent;title = title; return r, }: { _. [] });_. console;log(tree);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.