Skip to content
31 changes: 29 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ Which results in the following array:

You can provide a second argument to arrayToTree with configuration options. Right now, you can set the following:

- `id`: key of the id field of the item
- `parentId`: key of the parent's id field of the item
- `id`: key of the id field of the item. Default: `"id"`
- `parentId`: key of the parent's id field of the item. Default: `"parentId"`
- `dataField`: key which will contain all properties/data of the origina items. Set to null if you don't want a container. Default: `"data"`

Example:

Expand Down Expand Up @@ -88,6 +89,32 @@ Which produces:
]
```

Example with no data field:

```js
const tree = arrayToTree([
{ id: '4', parentId: null, custom: 'abc' },
{ id: '31', parentId: '4', custom: '12' },
{ id: '1941', parentId: '418', custom: 'de' },
{ id: '1', parentId: '418', custom: 'ZZZz' },
{ id: '418', parentId: null, custom: 'ü'},
], { dataField: null })
```

Which produces:

```js
[
{ id: '4', parentId: null, custom: 'abc', children: [
{ id: '31', parentId: '4', custom: '12', children: [] },
] },
{ id: '418', parentId: null, custom: 'ü', children: [
{ id: '1941', parentId: '418', custom: 'de', children: [] },
{ id: '1', parentId: '418', custom: 'ZZZz', children: [] },
] },
]
```

## TypeScript

This project includes types, just import the module as usual:
Expand Down
11 changes: 7 additions & 4 deletions build/arrayToTree.d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
export interface Item {
id: string;
parentId: string | null;
id?: string;
parentId?: string | null;
[key: string]: any;
}
export interface TreeItem {
data: Item | null;
id?: string;
parentId?: string | null;
[key: string]: Item | any;
children: TreeItem[];
}
export interface Config {
id: string;
parentId: string;
dataField: string | null;
}
/**
* Unflattens an array to a tree with runtime O(n)
*/
export declare function arrayToTree(items: Item[], config?: Config): TreeItem[];
export declare function arrayToTree(items: Item[], config?: Partial<Config>): TreeItem[];
34 changes: 28 additions & 6 deletions build/arrayToTree.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion build/arrayToTree.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion build/arrayToTree.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 66 additions & 2 deletions build/arrayToTree.spec.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading