gpt4 book ai didi

javascript - JS从一组URL创建树

转载 作者:行者123 更新时间:2023-11-30 13:48:33 24 4
gpt4 key购买 nike

我在从给定的 URL 数组创建树时遇到了一些困难。主要目标是将 url 拆分成段,并将它们排列成父子关系。例如给定数组:

   const data =  [
{
'id': '1',
'name': '/home',
},
{
'id': '2',
'name': '/story',
},
{
'id': '3',
'name': '/story/summer-story',
},
{
'id': '4',
'name': '/story/summer-story/2019',
},
]

输出应该是:

const tree = [
{
'id': '1',
'name' : '/home',
children: []
},
{
'id': '2',
'name': '/story',
'children': [
{
'id' : '3',
'name': '/story/summer-story',
'children': [
{
'id': '4',
'name': '/story/summer-story/2019'
}
]
},
]
}
]

我已经使用 Javascript deriving a Tree from a set of URLs 中的示例创建了某种解决方案

当有一个或两个段的 url 时,我当前的解决方案工作正常。一旦它有两个以上的段,它就会在根级别添加节点,而不是嵌套到下降的父节点中。

示例代码

export const addToTree = (node, treeNodes) => {
const parentNode = getTheParentNodeChildArray(node.name, treeNodes) || treeNodes;

parentNode.push({
title: node.title,
name: node.name,
children: []
});
};

export const getTheParentNodeChildArray = (path, treeNodes) => {
for (let i = 0; i < treeNodes.length; i++) {
const treeNode = treeNodes[i];

const lastSegment = getStringWithoutLastSegment(path);
const lastNode = getStringWithoutLastSegment(treeNode.name);

if (lastNode === lastSegment) {
return treeNode.children;
}
else if (treeNode.children.length > 0) {
let possibleParent = false;

treeNode.children.forEach(function(item) {
const lastSegmentPath = getStringWithoutLastSegment(path);
const lastSegmentItem = getStringWithoutLastSegment(item.name);

if (lastSegmentItem === lastSegmentPath) {
possibleParent = true;
return false;
}
});

if (possibleParent) {
return getTheParentNodeChildArray(path, treeNode.children);
}
}
}
};

export const createTree = (nodes) => {
const tree = [];

for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
addToTree(node, tree);
}
return tree;
};

export const getStringWithoutLastSegment = (str) => {
const stringArray = str.split('/');
stringArray.pop();
return (stringArray.join('/'));
};

提前致谢

最佳答案

这可以在一个函数中直接完成。该方法涉及遍历所有要添加的节点,然后逐个目录遍历树目录,根据需要创建节点。最终的结果不是一棵树,因为有多个根,但在构建它时有一个虚拟根是有帮助的。

const makeTree = data => {
const base = {children: []};

for (const node of data) {
const path = node.name.match(/\/[^\/]+/g);
let curr = base;

path.forEach((e, i) => {
const currPath = path.slice(0, i + 1).join("");
const child = curr.children.find(e => e.name === currPath);

if (child) {
curr = child;
}
else {
curr.children.push({
id: node.id, name: currPath, children: []
});
curr = curr.children[curr.children.length-1];
}
});
}

return base.children;
};

const data = [
{
'id': '1',
'name': '/home',
},
{
'id': '2',
'name': '/story',
},
{
'id': '3',
'name': '/story/summer-story',
},
{
'id': '4',
'name': '/story/summer-story/2019',
},
];

console.log(makeTree(data));

关于javascript - JS从一组URL创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58784797/

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