Skip to content

Commit b716044

Browse files
author
Philipp Alferov
committed
Allow to set up children property
1 parent 8308843 commit b716044

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

index.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ var assign = require('lodash.assign');
33
var property = require('nested-property');
44
var keyBy = require('lodash.keyby');
55

6-
var createTree = function(array, rootNodes, customID) {
6+
var createTree = function(array, rootNodes, customID, childrenProperty) {
77
var tree = [];
88

99
for (var rootNode in rootNodes) {
@@ -15,7 +15,12 @@ var createTree = function(array, rootNodes, customID) {
1515
}
1616

1717
if (childNode) {
18-
node.children = createTree(array, childNode, customID);
18+
node[childrenProperty] = createTree(
19+
array,
20+
childNode,
21+
customID,
22+
childrenProperty
23+
);
1924
}
2025

2126
tree.push(node);
@@ -55,8 +60,10 @@ var groupByParents = function(array, options) {
5560
* @param {Object} options An object containing the following fields:
5661
*
5762
* - `parentProperty` (String): A name of a property where a link to
58-
* a parent node could be found. Default: 'parent_id'
63+
* a parent node could be found. Default: 'parent_id'
5964
* - `customID` (String): An unique node identifier. Default: 'id'
65+
* - `childrenProperty` (String): A name of a property where chilren nodes
66+
* are going to be stored. Default: 'children'.
6067
*
6168
* @return {Array} Result of transformation
6269
*/
@@ -65,6 +72,7 @@ module.exports = function arrayToTree(data, options) {
6572
options = assign(
6673
{
6774
parentProperty: 'parent_id',
75+
childrenProperty: 'children',
6876
customID: 'id',
6977
rootID: '0'
7078
},
@@ -76,5 +84,10 @@ module.exports = function arrayToTree(data, options) {
7684
}
7785

7886
var grouped = groupByParents(data, options);
79-
return createTree(grouped, grouped[options.rootID], options.customID);
87+
return createTree(
88+
grouped,
89+
grouped[options.rootID],
90+
options.customID,
91+
options.childrenProperty
92+
);
8093
};

test/test.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,18 +120,19 @@ describe('array-to-tree', function() {
120120
],
121121
{
122122
parentProperty: 'parent',
123-
customID: '_id'
123+
customID: '_id',
124+
childrenProperty: '_children'
124125
}
125126
)
126127
).to.be.deep.equal([
127128
{
128129
_id: 'ec654ec1-7f8f-11e3-ae96-b385f4bc450c',
129130
parent: null,
130-
children: [
131+
_children: [
131132
{
132133
_id: 'ec666030-7f8f-11e3-ae96-0123456789ab',
133134
parent: 'ec654ec1-7f8f-11e3-ae96-b385f4bc450c',
134-
children: [
135+
_children: [
135136
{
136137
_id: 'ec66fc70-7f8f-11e3-ae96-000000000000',
137138
parent: 'ec666030-7f8f-11e3-ae96-0123456789ab'

0 commit comments

Comments
 (0)