Convert an array of parent-child relational objects to a tree.
npm install --save sapling
Create a new Sapling and pass the collection as first argument. The
properties name
and parent
are used by default to identify each node.
var Sapling = require('sapling')
, sapling = new Sapling([{
name: 'node1'
}, {
name: 'node2',
parent: 'node1'
}]);
This will result in the following tree:
{
name: 'node1',
children: [{
name: 'node2',
parent: 'node1',
children: []
}]
}
If nodes and the parent are identified by different properties then
supply the names as arguments to Sapling
. The id
as second argument
and the parent
reference as third argument.
var Sapling = require('sapling')
, sapling = new Sapling([{
id: 'node1'
}, {
id: 'node2',
reference: 'node1'
}], 'id', 'reference');
npm run test
npm run coverage
To walk or traverse the generate tree, either implement a custom iterator with ES6 or use the module named t. The latter is compatible and uses the same tree structure.
Sapling is released under MIT.