Skip to content

Commit dd847c4

Browse files
Merge pull request #21 from gregoryforel/nested-item-properties
Nested item properties
2 parents 4fe9dc2 + eb55f26 commit dd847c4

File tree

9 files changed

+535
-266
lines changed

9 files changed

+535
-266
lines changed

README.md

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ Which results in the following array:
5959

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

62-
- `id`: key of the id field of the item. Default: `"id"`
63-
- `parentId`: key of the parent's id field of the item. Default: `"parentId"`
62+
- `id`: key of the id field of the item. Also works with nested properties (e. g. `"nested.parentId"`). Default: `"id"`.
63+
- `parentId`: key of the parent's id field of the item. Also works with nested properties (e. g. `"nested.parentId"`). Default: `"parentId"`.
6464
- `childrenField`: key which will contain all child nodes of the parent node. Default: `"children"`
6565
- `dataField`: key which will contain all properties/data of the original items. Set to null if you don't want a container. Default: `"data"`
6666
- `throwIfOrphans`: option to throw an error if the array of items contains one or more items that have no parents in the array. This option has a small runtime penalty, so it's disabled by default. When enabled, the function will throw an error containing the parentIds that were not found in the items array. When disabled, the function will just ignore orphans and not add them to the tree. Default: `false`
@@ -118,6 +118,25 @@ Which produces:
118118
]
119119
```
120120

121+
Example with nested id/parentId properties:
122+
123+
```js
124+
const tree = arrayToTree([
125+
{ num: { id: '4' }, parent: { parentId: null }, custom: 'abc' },
126+
{ num: { id: '31' }, parent: { parentId: '4' }, custom: '12' },
127+
], { id: 'num.id', parentId: 'parent.parentId' })
128+
```
129+
130+
Which produces:
131+
132+
```js
133+
[
134+
{ data: { num: { id: '4' }, parent: { parentId: null }, custom: 'abc' }, children: [
135+
{ data: { num: { id: '31' }, parent: { parentId: '4' }, custom: '12' }, children: [] },
136+
] },
137+
]
138+
```
139+
121140
## TypeScript
122141

123142
This project includes types, just import the module as usual:

build/arrayToTree.js

Lines changed: 12 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

build/arrayToTree.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

build/arrayToTree.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)