I have an array of objects from which I would like to group by a property to build a tree structure.
objects = [object1, object2, object3, ... ]
Object example:
object1 = {
FolderName: "Folder1", //group on this property
NodeName: "Node1"
}
I want to group objects by the FolderName property to get a tree structure like this:
treeData = [
{
text: "Folder1",
nodes: [
{
text: "Node1",
}
]
},
{
text: "Folder2",
nodes : [
{
text: "NodeX",
}
]
}
]
Edit:
I was trying with this groupBy function but it returns an array of arrays. So I transform it into the tree structure I need with the for loop. I got the result I want but I wander how to achieve it in a more optimal way.
function groupBy(array, f) {
var groups = {};
array.forEach(function(o){
var group = JSON.stringify(f(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map(function(group){
return groups[group];
});
}
var result = groupBy(objects, function(item){
item.text = item.NodeName;
return [item.FolderName];
});
var treeData = [];
for (i=0; i < result.length; i++) {
treeData.push({ "text": result[i][0].FolderName, "nodes":result[i]});
}