I've hobbled together a solution, but it doesn't feel very clean and is probably prone to breakage:
var nested = [];
for (var i=0; i < flat.length; i++) {
// split components up
var routes = flat[i].path.split(".");
// get parent key
var key = routes[0];
// check if we've already added the key
var index = -1;
for (var j=0; j < nested.length; j++) {
if (nested[j].path == key) {
index = j;
break;
}
}
if (index===-1) {
// if we have a new parent add it
nested.push(flat[i])
} else {
// create subpaths property on new object
if (!nested[index].subpaths) { nested[index].subpaths = [] }
// add child paths to existing parent
nested[index].subpaths.push(flat[i])
}
}
var flat = [
{path: "/" },
{path: "A" },
{path: "A.A"},
{path: "A.B"},
{path: "A.C"},
{path: "B" },
{path: "C" }
]
var nested = [];
for (var i=0; i < flat.length; i++) {
// split components up
var routes = flat[i].path.split(".");
// get parent key
var key = routes[0];
// check if we've already added the key
var index = -1;
for (var j=0; j < nested.length; j++) {
if (nested[j].path == key) {
index = j;
break;
}
}
if (index===-1) {
// if we have a new parent add it
nested.push(flat[i])
} else {
// create subpaths property on new object
if (!nested[index].subpaths) { nested[index].subpaths = [] }
// add child paths to existing parent
nested[index].subpaths.push(flat[i])
}
}
console.log(nested);
I'm also open to using jQuery or Underscore if they expose any functionality that would tidy up the source code. I'd also like to modify the code so it could handle this recursively with an unspecified level of depth on each node.