Skip to content

Commit 9ea1978

Browse files
committed
Updated readme with nested property example
1 parent b4d73ef commit 9ea1978

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

README.md

Lines changed: 37 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. Default: `"id"`. It also works with nested properties (`"myobject.nestedObject.id"`), see examples below
63+
- `parentId`: key of the parent's id field of the item. Default: `"parentId"`. It also works with nested properties (`"myobject.nestedObject.parentId"`), see examples below
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`
@@ -91,6 +91,41 @@ Which produces:
9191
]
9292
```
9393

94+
Nested properties (id and/or parentId are nested inside your objects)
95+
```js
96+
const tree = arrayToTree([
97+
{ nestedObject: { num: '4', ref: null, custom: 'abc' } },
98+
{ nestedObject: { num: '31', ref: '4', custom: '12' } },
99+
{ nestedObject: { num: '1941', ref: '418', custom: 'de' } },
100+
{ nestedObject: { num: '1', ref: '418', custom: 'ZZZz' } },
101+
{ nestedObject: { num: '418', ref: null, custom: 'ü'} },
102+
], { id: 'nestedObject.num', parentId: 'nestedObject.ref', childrenField: 'nodes' })
103+
```
104+
105+
Which produces:
106+
107+
```js
108+
[
109+
{
110+
data: nestedObject {
111+
{ num: '4', ref: null, custom: 'abc' },
112+
nodes: [
113+
{ data: nestedObject { { num: '31', ref: '4', custom: '12' }, nodes: [] } },
114+
]
115+
}
116+
},
117+
{
118+
data: nestedObject {
119+
{ num: '418', ref: null, custom: 'ü'},
120+
nodes: [
121+
{ data: nestedObject { { num: '1941', ref: '418', custom: 'de' }, nodes: [] } },
122+
{ data: nestedObject { { num: '1', ref: '418', custom: 'ZZZz' }, nodes: [] } },
123+
]
124+
}
125+
},
126+
]
127+
```
128+
94129
Example with no data field:
95130

96131
```js

0 commit comments

Comments
 (0)