Tree utils for javascript.
In most projects, the use of tree structures to simplify data structures, expand or collapse menus. This library gives you tools to convert an array to a tree, and vice versa. In addition, also supports the arrangement by tree structure, calculate the values of subtracting leaves on tree branches and stumps ...
to use in javascript in browser or angluar or react or nodejs
npm install cng-tree-utils
node ./tree-utils/test/test-array-2-tree.js
node ./tree-utils/test/test-array-2-order-by-tree.js
node ./tree-utils/test/test-tree-2-array.js
Make array to tree
const test = require ( " cng-tree-utils " ) ;
let arr = [
{
id : 1
, name : " A "
, total : 0
} ,
{
id : 2
, name : " B "
, total : 1
} ,
{
id : 3
, parent : 2
, name : " B.1 "
, total : 2
} ,
{
id : 4
, parent : 1
, name : " A.1 "
, total : 3
} ,
{
id : 5
, parent : 2
, name : " B.2 "
, total : 4
} ,
{
id : 6
, parent : 3
, name : " B.1.1 "
, total : 5
} ,
] ;
console . log ( " Origin ARRAY ***> \n " , JSON . stringify ( arr , null , 2 ) ) ;
let arr2Tree = test . array2Tree ( arr , " id " , " parent " ) ;
console . log ( " array to TREE --> \n " , JSON . stringify ( arr2Tree , null , 2 ) ) ;
Sort Array by Tree structure:
const test = require ( " cng-tree-utils " ) ;
let arr = [
{
id : 1
, name : " A "
, total : 0
} ,
{
id : 2
, name : " B "
, total : 1
} ,
{
id : 3
, parent : 2
, name : " B.1 "
, total : 2
} ,
{
id : 4
, parent : 1
, name : " A.1 "
, total : 3
} ,
{
id : 5
, parent : 2
, name : " B.2 "
, total : 4
} ,
{
id : 6
, parent : 3
, name : " B.1.1 "
, total : 5
} ,
] ;
console . log ( " Origin ARRAY ***> \n " , JSON . stringify ( arr , null , 2 ) ) ;
let arr2Order = test . array2SortByTree ( arr , " id " , " parent " ) ;
console . log ( " array to Order --> \n " , JSON . stringify ( arr2Order , null , 2 ) ) ;
let arrOrderWeight = test . array2SortAndWeight ( arr , " id " , " parent " , " total " ) ;
console . log ( " array to Order --> \n " , JSON . stringify ( arrOrderWeight , null , 2 ) ) ;
Convert tree structure into Array:
const test = require ( " cng-tree-utils " ) ;
let arrOrigin =
[
{
" id " : 1 ,
" name " : " A " ,
" total " : 0 ,
" subs " : [
{
" id " : 4 ,
" parent " : 1 ,
" name " : " A.1 " ,
" total " : 3
}
]
} ,
{
" id " : 2 ,
" name " : " B " ,
" total " : 1 ,
" subs " : [
{
" id " : 3 ,
" parent " : 2 ,
" name " : " B.1 " ,
" total " : 2 ,
" subs " : [
{
" id " : 6 ,
" parent " : 3 ,
" name " : " B.1.1 " ,
" total " : 5
}
]
} ,
{
" id " : 5 ,
" parent " : 2 ,
" name " : " B.2 " ,
" total " : 4
}
]
}
]
console . log ( " Origin ARRAY ***> \n " , JSON . stringify ( arrOrigin , null , 2 ) ) ;
let tree2Arr = test . tree2Array ( arrOrigin , " subs " ) ;
console . log ( " \n *************> \n tree to ARRAY --> \n " , tree2Arr ) ;
Hope to help you in handling flat tree data types like in SQL and NoSQL database structures, like sqlite2, mongodb, oracle, mySql without having to use sql clauses inside database.