@build-tree/tools
v1.0.8
Published
将扁平数据转换为树状结构
Downloads
29
Readme
@build-tree/tools 工具使用指南
功能概述
@build-tree/tools 是一款基于 TypeScript 开发的实用工具,可以将扁平数据转成树状结构。
安装方式
使用npm安装
npm install @build-tree/tools使用pnpm安装
pnpm add @build-tree/tools核心特性
- 高性能转换:采用两次遍历算法,时间复杂度O(n)
- 灵活配置:支持自定义ID和父ID字段名
- 安全警告:自动检测超大子树并发出性能警告
- 零依赖:不增加项目体积
- 类型安全:完整的TypeScript支持(需配合.d.ts文件使用)
基本用法
import { buildTree } from '@build-tree/tools';
const flatData = [
{ id: 1, name: '根节点' },
{ id: 2, parentId: 1, name: '子节点1' },
{ id: 3, parentId: 1, name: '子节点2' }
];
const tree = buildTree(flatData);
/* 输出:
[
{
id: 1,
name: '根节点',
children: [
{ id: 2, parentId: 1, name: '子节点1', children: [] },
{ id: 3, parentId: 1, name: '子节点2', children: [] }
]
}
]
*/高级用法
自定义字段名
const tree = buildTree(data, {
idKey: 'uid',
parentIdKey: 'pid'
});处理大型数据集
// 调整警告阈值
const tree = buildTree(largeData, {
maxChildrenWarning: 5000
});
// 禁用警告
const tree = buildTree(largeData, {
maxChildrenWarning: Infinity
});配置选项
| 参数 | 类型 | 默认值 | 描述 |
| -------------------- | ------ | ---------- | ---------------------------- |
| idKey | string | 'id' | 节点唯一标识字段名 |
| parentIdKey | string | 'parentId' | 父节点引用字段名 |
| maxChildrenWarning | number | 1000 | 触发性能警告的子节点数量阈值 |
性能优化建议
合理设置阈值:根据实际场景调整maxChildrenWarning值
