Manipulate and traverse tree-like structures in javascript.
TreeModel.js |
TreeModel-min.js (v1.0.7)
These bundles are UMD compatible (courtesy of browserify)
Create a new TreeModel
// hint: TreeModel, tree and root are
// globally available on this page
tree = new TreeModel();
root = tree.parse({
id: 1,
children: [
{
id: 11,
children: [{id: 111}]
},
{
id: 12,
children: [{id: 121}, {id: 122}]
},
{
id: 13
}
]
});
Find the first node that matches a predicate
var node12 = root.first(function (node) {
return node.model.id === 12;
});
Find all nodes that match a predicate
var nodesGt100 = root.all(function (node) {
return node.model.id > 100;
});
Traverse the tree
root.walk(function (node) {
// Halt the traversal by returning false
if (node.model.id === 121) return false;
});
Drop a node
// Dropping a node returns the node itself
node12.drop();
Add a node
// Parse the new node
node123 = tree.parse({id: 123, children: [{id: 1231}]});
// Add it to the parent
node12.addChild(node123);
Get a node's path
node122.getPath();
// [<node 1>, <node 12>, <node 122>]