写一个方法将数组转结构换为tree,要求性能好
在前端开发中,将扁平化的数组转换为树形结构是一个常见的需求。以下是一个使用JavaScript实现的高性能方法,它基于递归和哈希表来构建树形结构:
function arrayToTree(items, parentId = null) {
const tree = [];
const lookup = {}; // 用于快速查找节点的哈希表
// 首先,将所有节点添加到查找表中,以便后续快速访问
items.forEach(item => {
const itemId = item.id; // 假设每个节点都有一个唯一的id属性
const itemParentId = item.parentId || parentId; // 父节点的id,根节点使用传入的parentId,默认为null
lookup[itemId] = { ...item, children: [] }; // 初始化节点的children属性为空数组
if (itemParentId == null) {
tree.push(lookup[itemId]); // 根节点直接添加到树中
} else {
const parent = lookup[itemParentId];
if (parent) {
parent.children.push(lookup[itemId]); // 将节点添加到其父节点的children数组中
}
}
});
return tree;
}
// 示例用法:
const items = [
{ id: 1, name: 'Root1' },
{ id: 2, name: 'Child1', parentId: 1 },
{ id: 3, name: 'Child2', parentId: 1 },
{ id: 4, name: 'Grandchild1', parentId: 2 },
{ id: 5, name: 'Root2' },
{ id: 6, name: 'Child3', parentId: 5 },
];
const tree = arrayToTree(items);
console.log(JSON.stringify(tree, null, 2));
这个方法首先遍历所有节点,将它们添加到一个哈希表(lookup
)中,以便后续能够快速查找。同时,它会检查每个节点的父节点ID,如果父节点ID为null,说明该节点是根节点,直接将其添加到树中。否则,它会查找父节点,并将当前节点添加到父节点的children
数组中。
这种方法的时间复杂度为O(n),其中n是节点的数量。由于它只遍历了一次数组,并且使用了哈希表来加速节点查找,因此性能较高。
注意:上述代码假设每个节点都有一个唯一的id
属性和一个可选的parentId
属性来表示其父节点的ID。如果你的数据结构与此不同,请相应地调整代码。