sapling
v1.0.0
Published
Convert an array of parent-child relational objects to a tree
Downloads
9
Maintainers
Readme
Sapling
Convert an array of parent-child relational objects to a tree.
Installation
npm install --save sapling
Usage
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');
Tests
npm run test
npm run coverage
Traversal
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.
License
Sapling is released under MIT.