I have data as following: `
[
{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"},
]
` and i need something like:-
`
[
{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: []
}
]
`
so far i have written this but its not helping me at all. `
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);
`
There can be various paths. they are coming dynamically. i need to set them as children. i need to do this in Javascript code.Appreciate your help. Thanks.
You could take a shadow tree and assign the title later to the the structure.
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.