to-tree-smart
v1.0.4
Published
A smart and efficient tree data structure converter that transforms flat arrays into hierarchical tree structures
Maintainers
Readme
to-tree-smart
一个智能高效的树形数据结构转换器,可以将扁平数组转换为层级树形结构。
特性
- 高性能: 使用 Map 数据结构实现,时间复杂度为 O(n)
- 安全: 自动进行浅拷贝,不修改原始数据,同时保留函数和 Symbol 等特殊属性
- 类型安全: 完整的 TypeScript 支持
- 灵活配置: 支持自定义字段名
- 零依赖: 不依赖任何第三方库
- 易于使用: 简洁的 API 设计
安装
npm install to-tree-smart或使用 yarn:
yarn add to-tree-smart或使用 pnpm:
pnpm add to-tree-smart使用方法
基本用法
import { toTreeSmart } from "to-tree-smart";
const flatData = [
{ id: 1, name: "Root", parentId: null },
{ id: 2, name: "Child 1", parentId: 1 },
{ id: 3, name: "Child 2", parentId: 1 },
{ id: 4, name: "Grandchild", parentId: 2 },
];
const tree = toTreeSmart(flatData);
console.log(tree);
// 输出:
// [
// {
// id: 1,
// name: 'Root',
// parentId: null,
// children: [
// {
// id: 2,
// name: 'Child 1',
// parentId: 1,
// children: [
// { id: 4, name: 'Grandchild', parentId: 2 }
// ]
// },
// { id: 3, name: 'Child 2', parentId: 1 }
// ]
// }
// ]自定义字段名
import { toTreeSmart } from "to-tree-smart";
const flatData = [
{ key: 1, name: "Root", pid: null },
{ key: 2, name: "Child", pid: 1 },
];
const tree = toTreeSmart(flatData, {
idKey: "key",
parentIdKey: "pid",
childrenKey: "items",
});保留空的 children 数组
import { toTreeSmart } from "to-tree-smart";
const flatData = [
{ id: 1, name: "Root", parentId: null },
{ id: 2, name: "Leaf", parentId: 1 },
];
const tree = toTreeSmart(flatData, {
keepEmptyChildren: true,
});
// Leaf 节点将会保留 children: []API
toTreeSmart(data, options?)
将扁平数组转换为树形结构。
参数
data: T[]- 要转换的扁平数组options?: ToTreeSmartOptions- 配置选项(可选)
配置选项
interface ToTreeSmartOptions {
/** ID 字段名,默认为 'id' */
idKey?: string;
/** 父 ID 字段名,默认为 'parentId' */
parentIdKey?: string;
/** 子节点字段名,默认为 'children' */
childrenKey?: string;
/** 是否保留空的 children 数组,默认为 false */
keepEmptyChildren?: boolean;
}返回值
返回树形结构的根节点数组 T[]
TypeScript 支持
该包完全使用 TypeScript 编写,包含完整的类型定义。
import { toTreeSmart, TreeNode, ToTreeSmartOptions } from 'to-tree-smart';
interface MyNode extends TreeNode {
name: string;
// 其他自定义字段...
}
const data: MyNode[] = [...];
const tree = toTreeSmart<MyNode>(data);性能
该函数使用 Map 数据结构实现,具有以下时间复杂度:
- 时间复杂度: O(n),其中 n 是数组长度
- 空间复杂度: O(n)
相比传统的递归方法(时间复杂度 O(n)),性能提升显著,特别是在处理大量数据时。
License
MIT
贡献
欢迎提交 Issue 和 Pull Request!
作者
whitsats
