builtTree
by Johan Vandeplas
JavaScript
var uniqueId = 0,
separator = '//',
buildTree = function (rawData) {
var rootNode = {
children: []
},
getNode = function (node, setLabel) {
var i, n;
for (i = 0; i < node.children.length; i++) {
if (node.children[i].leaf === false && node.children[i].name === setLabel) {
return node.children[i];
}
}
n = {
id: uniqueId++,
name: setLabel,
children: [],
leaf: false
};
node.children.push(n);
return n;
},
addInPath = function (o) {
var path = o.name.split(separator),
node = rootNode;
for (var i = 0; i < path.length; i++) {
var setLabel = path[i];
if (i === path.length - 1) {
o.name = setLabel;
node.children.push(o);
} else {
node = getNode(node, setLabel);
}
}
};
for (var i = 0; i < rawData.length; i++) {
addInPath(rawData[i]);
}
return rootNode;
};
console.log(buildTree([{
"id": 1,
"name": "nodeA"
}, {
"id": 2,
"name": "A//nodeB"
}, {
"id": 3,
"name": "A//B//nodeC"
}, {
"id": 4,
"name": "A//B//nodeD"
}, {
"id": 5,
"name": "A//F//G/nodeE"
}, {
"id": 6,
"name": "A//B//E//nodeF"
}, {
"id": 7,
"name": "C//nodeG"
}]));