11'use strict' ;
22var isArray = require ( 'isarray' ) ;
3- var extend = require ( 'shallow-object- extend' ) ;
4- var exists = require ( 'property-exists' ) ;
3+ var extend = require ( 'extend' ) ;
4+ var exists = require ( 'property-exists' ) ;
55
66var createTree = function ( array , rootNodes , customID ) {
77 var tree = [ ] ;
88
99 for ( var rootNode in rootNodes ) {
10- if ( ! exists ( rootNodes , rootNode ) ) {
11- continue ;
12- }
1310 var node = rootNodes [ rootNode ] ;
1411 var childNode = array [ node [ customID ] ] ;
1512
13+ if ( ! node && ! exists ( rootNodes , rootNode ) ) {
14+ continue ;
15+ }
16+
1617 if ( childNode ) {
1718 node . children = createTree ( array , childNode , customID ) ;
1819 }
@@ -25,15 +26,16 @@ var createTree = function(array, rootNodes, customID) {
2526
2627var groupByParents = function ( array , options ) {
2728 var parents = { } ;
28- var parentProperty = options . parentProperty ;
2929
3030 array . forEach ( function ( item ) {
31- var parentID = item [ parentProperty ] || options . rootID ;
32- if ( exists ( parents , parentID ) ) {
31+ var parentID = item [ options . parentProperty ] || options . rootID ;
32+
33+ if ( parentID && exists ( parents , parentID ) ) {
3334 parents [ parentID ] . push ( item ) ;
34- } else {
35- parents [ parentID ] = [ item ] ;
35+ return ;
3636 }
37+
38+ parents [ parentID ] = [ item ] ;
3739 } ) ;
3840
3941 return parents ;
@@ -63,10 +65,10 @@ module.exports = function arrayToTree(data, options) {
6365 parentProperty : 'parent_id' ,
6466 customID : 'id' ,
6567 rootID : '0'
66- } , options || { } ) ;
68+ } , options ) ;
6769
6870 if ( ! isArray ( data ) ) {
69- throw new Error ( 'Expected an object but got an invalid argument' ) ;
71+ throw new TypeError ( 'Expected an object but got an invalid argument' ) ;
7072 }
7173
7274 var cloned = data . slice ( ) ;
0 commit comments