createTree
JavaScript
registerMixins();
var data = getJSON();
_.each(data, function createTree( item, index ) {
item.originalIndex = index;
if ( !item.parent ) { return false; }
var itemParent = _.findWhereRecursive(data, {id: item.parent});
if ( !itemParent ) { return false; }
itemParent.children = itemParent.children || [];
itemParent.children.push(item);
data.splice(index, 1);
});
console.log(data)
function registerMixins() {
_.mixin({
indexOfObject: function ( array, object, property, fromIndex ) {
if (!fromIndex) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, array.length + fromIndex);
}
for (var i = fromIndex, j = array.length; i < j; i++) {
if ( property && array[i][property] == object[property] )
return i;
}
return -1;
},
findWhereRecursive: function ( array, attrs ) {
return _.chain(array).map(function (value) {
for ( key in attrs )
if ( attrs[key] === value[key] )
return value;
if ( value.children )
return _.findWhereRecursive(value.children, attrs);
}).compact().value();
}
});
}
function getJSON() {
return [{"id":"competency.4894","text":"Centralized concept","prefix":"competency","cvalue":"competency.4894","covalue":4894,"cid":"competency.31","disabled":false,"scale":{"id":5,"value":"Vezetői engedélyek"},"parent":null},{"id":"competency.13818","text":"Business-focused superstructure","prefix":"competency","cvalue":"competency.13818","covalue":13818,"cid":"competency.57","disabled":false,"scale":{"id":2,"value":"Végzettség szintje"},"parent":null},{"id":"competency.3689","text":"Triple-buffered pricing...