我正在通过将路径数组转换为树视图数据结构来构建树视图。以下是我想做的:
// routes are sorted.
let routes = [
['top', '1.jpg'],
['top', '2.jpg'],
['top', 'unsplash', 'photo.jpg'],
['top', 'unsplash', 'photo2.jpg'],
['top', 'foo', '2.jpg'],
['top', 'foo', 'bar', '1.jpg'],
['top', 'foo', 'bar', '2.jpg']
];
into
let treeview = {
name: 'top', child: [
{name: '1.jpg', child: []},
{name: '2.jpg', child: []},
{name: 'unsplash', child: [
{name: 'photo.jpg', child: []},
{name: 'photo2.jpg', child: []}
]},
{name: 'foo', child: [
{name: '2.jpg', child: []},
{name: 'bar', child: [
{name: '1.jpg', child: []},
{name: '2.jpg', child: []}
]}
]}
]}
现在,我已经通过此方法成功地转换了单个项目数组,但无法对多个数组进行转换。还要注意,嵌套的treeview不包含重复项。
function nest(arr) {
let out = [];
arr.map(it => {
if(out.length === 0) out = {name: it, child: []}
else {
out = {name: it, child: [out]}
}
});
return out;
}