gpt4 book ai didi

javascript - 从对象构建目录树

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:06 27 4
gpt4 key购买 nike

具有以下格式的项目数组:

[ { path: '/Folder 1/Folder 1.1',
name: 'Folder 1.1.1',
id: 'Fi6CsP4RWFutOZKsIDoYMSfBPQb-A-lj3C4Jc_zZoG0' },
{ path: '/Folder 1',
name: 'Folder 1.2',
id: 'c2dTN3CgBr9Xik8jdpBkfzR6wZ00oGTX3IbfXrfFujM' },
{ path: '/Folder 1',
name: 'Folder 1.1',
id: 'WmKaOZhzpubcunNNoxbUnqfSYVuNQZDNC852KDJK_G8' },
{ path: '/',
name: 'Folder 1',
id: 'aNRvIvCLyNOgLOmZVzFhoOiZMAz3-p87kBFIGSQS2Yg' },
{ path: '/',
name: 'Folder 2',
id: 'S4FkkQ3hgLTVedIrlSBqe2_1DhrrnLx5szk7-9Wv3X8' } ]

可以把它变成像下面这样的格式

var dir = {
"directory": [{
"text": "Folder 1",
"id": 'aNRvIvCLyNOgLOmZVzFhoOiZMAz3-p87kBFIGSQS2Yg',
"nodes": [{
"text": "Folder 1.1",
"id": 'WmKaOZhzpubcunNNoxbUnqfSYVuNQZDNC852KDJK_G8',
"nodes": [{
"text": "Folder 1.1.1",
"id": 'Fi6CsP4RWFutOZKsIDoYMSfBPQb-A-lj3C4Jc_zZoG0'
}]
}, {
"text": "Folder 1.2",
"id": 'c2dTN3CgBr9Xik8jdpBkfzR6wZ00oGTX3IbfXrfFujM'
}]
},
{
"text": "Folder 2",
"id": 'S4FkkQ3hgLTVedIrlSBqe2_1DhrrnLx5szk7-9Wv3X8'
}
]
};

图形化 Tree

我想用递归,但我还是没能做到。

最佳答案

这是一个非递归解决方案,它首先构建一棵树,然后将树转换为所需的结构。

第一步的原因是由于在线性时间内遍历 node 数组的速度很慢,并且没有假设平面输入数组的顺序。在对象树结构上执行查找可加快并简化过程,从而使结果树易于在单次遍历中构建。

const treeify = data => 
data.reduce((a, e) => {
let level = a;

e.path.split("/")
.filter(e => e)
.forEach(dir => {
if (!(dir in level)) {
level[dir] = {nodes: {}};
}

level = level[dir].nodes;
})
;

if (e.name in level) {
level[e.name] = {
text: e.name,
id: e.id,
nodes: level[e.name].nodes
};
}
else {
level[e.name] = {text: e.name, id: e.id};
}

return a;
}, {})
;

const format = tree => {
const result = [];
const stack = [[result, tree]];

while (stack.length) {
const [res, curr] = stack.pop();

for (const k in curr) {
const o = {
id: curr[k].id,
text: curr[k].text
};
res.push(o);

if (curr[k].nodes) {
o.nodes = [];
stack.push([o.nodes, curr[k].nodes]);
}
}
}

return {directory: result};
};

const data = [
{
path: '/Folder 1/Folder 1.1',
name: 'Folder 1.1.1',
id: 'Fi6CsP4RWFutOZKsIDoYMSfBPQb-A-lj3C4Jc_zZoG0'
},
{
path: '/Folder 1',
name: 'Folder 1.2',
id: 'c2dTN3CgBr9Xik8jdpBkfzR6wZ00oGTX3IbfXrfFujM'
},
{
path: '/Folder 1',
name: 'Folder 1.1',
id: 'WmKaOZhzpubcunNNoxbUnqfSYVuNQZDNC852KDJK_G8'
},
{
path: '/',
name: 'Folder 1',
id: 'aNRvIvCLyNOgLOmZVzFhoOiZMAz3-p87kBFIGSQS2Yg'
},
{
path: '/',
name: 'Folder 2',
id: 'S4FkkQ3hgLTVedIrlSBqe2_1DhrrnLx5szk7-9Wv3X8'
}
];

console.log(format(treeify(data)));

关于javascript - 从对象构建目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52489849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com