File tree Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Original file line number Diff line number Diff line change
1
+ export = arrayToTree ;
2
+
3
+ declare function arrayToTree < T > ( data : T [ ] , options ?: Partial < arrayToTree . Options > ) : Array < arrayToTree . Tree < T > > ;
4
+
5
+ declare namespace arrayToTree {
6
+ interface Options {
7
+ childrenProperty : string ;
8
+ parentProperty : string ;
9
+ customID : string ;
10
+ rootID : string ;
11
+ }
12
+
13
+ type Tree < T > = T & {
14
+ children ?: Array < Tree < T > > ;
15
+ } ;
16
+ }
Original file line number Diff line number Diff line change @@ -47,6 +47,23 @@ var groupByParents = function(array, options) {
47
47
} , { } ) ;
48
48
} ;
49
49
50
+ function isObject ( o ) {
51
+ return Object . prototype . toString . call ( o ) === '[object Object]' ;
52
+ }
53
+
54
+ function deepClone ( data ) {
55
+ if ( Array . isArray ( data ) ) {
56
+ return data . map ( deepClone ) ;
57
+ } else if ( isObject ( data ) ) {
58
+ return Object . keys ( data ) . reduce ( function ( o , k ) {
59
+ o [ k ] = deepClone ( data [ k ] ) ;
60
+ return o ;
61
+ } , { } ) ;
62
+ } else {
63
+ return data ;
64
+ }
65
+ }
66
+
50
67
/**
51
68
* arrayToTree
52
69
* Convert a plain array of nodes (with pointers to parent nodes) to a nested
@@ -82,7 +99,7 @@ module.exports = function arrayToTree(data, options) {
82
99
throw new TypeError ( 'Expected an object but got an invalid argument' ) ;
83
100
}
84
101
85
- var grouped = groupByParents ( data . slice ( ) , options ) ;
102
+ var grouped = groupByParents ( deepClone ( data ) , options ) ;
86
103
return createTree (
87
104
grouped ,
88
105
grouped [ options . rootID ] ,
You can’t perform that action at this time.
0 commit comments