从平面列表构建嵌套的HTML列表可以通过使用递归算法来实现。以下是一个示例的步骤:
const flatList = [
{ id: 1, name: 'Item 1', parentId: null },
{ id: 2, name: 'Item 1.1', parentId: 1 },
{ id: 3, name: 'Item 1.2', parentId: 1 },
{ id: 4, name: 'Item 1.2.1', parentId: 3 },
{ id: 5, name: 'Item 2', parentId: null },
{ id: 6, name: 'Item 2.1', parentId: 5 },
];
function buildNestedList(flatList, parentId = null) {
const nestedList = [];
// 遍历平面列表
for (const item of flatList) {
// 如果当前项的父级ID与传入的父级ID相同,则将其添加到嵌套列表中
if (item.parentId === parentId) {
// 递归调用buildNestedList函数,以当前项的ID作为父级ID,构建子级嵌套列表
const children = buildNestedList(flatList, item.id);
// 将当前项添加到嵌套列表中,并将子级嵌套列表作为其子项
nestedList.push({
id: item.id,
name: item.name,
children: children.length > 0 ? children : null,
});
}
}
return nestedList;
}
const nestedList = buildNestedList(flatList);
// 递归遍历嵌套列表,生成HTML列表
function generateHTMLList(nestedList) {
let html = '<ul>';
for (const item of nestedList) {
html += `<li>${item.name}`;
// 如果当前项有子级嵌套列表,则递归调用generateHTMLList函数生成子级HTML列表
if (item.children) {
html += generateHTMLList(item.children);
}
html += '</li>';
}
html += '</ul>';
return html;
}
const htmlList = generateHTMLList(nestedList);
console.log(htmlList);
这样,我们就可以从平面列表构建嵌套的HTML列表了。在上述示例中,我们使用了递归算法来处理嵌套列表的构建,通过遍历平面列表并根据父级ID来确定子级关系,最终生成了嵌套的HTML列表。
请注意,以上示例中的代码是基于JavaScript语言的,可以在浏览器的开发者工具中运行,或者在Node.js环境中执行。对于其他编程语言,可以根据相应语言的语法和特性进行相应的实现。
领取专属 10元无门槛券
手把手带您无忧上云