在前端开发中,经常需要将树形结构(nested structure)转换为平铺结构(flat structure),或者将平铺结构转换为树形结构。下面我会给出这两种转换的JavaScript示例代码。
树型数据转化为平铺数据
假设我们的树型数据是这样的:
const treeData = [
{
id: 1,
name: '节点1',
children: [
{ id: 2, name: '子节点1-1', children: [] },
{ id: 3, name: '子节点1-2', children: [] },
],
},
{
id: 4,
name: '节点2',
children: [],
},
// ...其他节点
];
转换为平铺数据的函数可能如下:
function flattenTree(tree, result = [], parentId = null) {
tree.forEach(node => {
const newNode = { ...node, parentId }; // 复制节点并添加parentId
delete newNode.children; // 删除children属性,因为现在是平铺结构
result.push(newNode); // 将节点添加到结果中
if (node.children) {
flattenTree(node.children, result, node.id); // 递归处理子节点
}
});
return result;
}
const flatData = flattenTree(treeData);
console.log(flatData);
平铺数据转化为树型数据
假设我们的平铺数据是这样的,每个节点都有一个parentId
指向其父节点(根节点的parentId
可以为null
或某个特定值,如0
):
const flatData = [
{ id: 1, name: '节点1', parentId: null },
{ id: 2, name: '子节点1-1', parentId: 1 },
{ id: 3, name: '子节点1-2', parentId: 1 },
{ id: 4, name: '节点2', parentId: null },
// ...其他节点
];
转换为树型数据的函数可能如下:
function buildTree(flatData, parentId = null) {
const tree = [];
const lookup = {}; // 用于快速查找父节点
// 第一步:创建一个哈希表,方便根据id查找节点
flatData.forEach(node => {
lookup[node.id] = { ...node, children: [] };
});
// 第二步:构建树形结构
flatData.forEach(node => {
if (node.parentId === parentId) {
const children = lookup[node.id].children;
delete lookup[node.id].parentId; // 不再需要parentId属性
Object.keys(lookup).forEach(childId => {
if (lookup[childId].parentId === node.id) {
children.push(lookup[childId]);
}
});
tree.push(lookup[node.id]);
}
});
return tree;
}
const treeDataAgain = buildTree(flatData);
console.log(treeDataAgain);
请注意,这些示例代码假设了每个节点都有一个唯一的id
属性,以及对于平铺结构数据,有一个parentId
属性来表示节点的父级。此外,对于平铺到树的转换,我们假设根节点的parentId
为null
(但在实际应用中,它可能是其他值,如0
或-1
)。在编写这些函数时,请确保它们与您的具体数据结构相匹配。