Skip to content

Instantly share code, notes, and snippets.

@enix-app
Forked from stephanbogner/index.js
Created September 12, 2020 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enix-app/1335469546354056a925777848a6e268 to your computer and use it in GitHub Desktop.
Save enix-app/1335469546354056a925777848a6e268 to your computer and use it in GitHub Desktop.
Create tree structure from paths array
var paths = [
["Account"],
["Account", "Payment Methods"],
["Account", "Payment Methods", "Credit Card"],
["Account", "Payment Methods", "Paypal"],
["Account", "Emails"],
["Account", "Emails", "Main Email"],
["Account", "Emails", "Backup Email"],
["Account", "Devices"],
["Account", "Devices", "Google Pixel"],
["Account", "Devices", "iPad Mini"],
["Account", "Devices", "Laptop"]
];
var tree = arrangeIntoTree(paths);
console.log(JSON.stringify(tree, null, 4));
// Result
// [
// {
// "name": "Account",
// "children": [
// {
// "name": "Payment Methods",
// "children": [
// {
// "name": "Credit Card",
// "children": []
// },
// {
// "name": "Paypal",
// "children": []
// }
// ]
// },
// {
// "name": "Emails",
// "children": [
// {
// "name": "Main Email",
// "children": []
// },
// {
// "name": "Backup Email",
// "children": []
// }
// ]
// },
// {
// "name": "Devices",
// "children": [
// {
// "name": "Google Pixel",
// "children": []
// },
// {
// "name": "iPad Mini",
// "children": []
// },
// {
// "name": "Laptop",
// "children": []
// }
// ]
// }
// ]
// }
// ]
function arrangeIntoTree(paths) {
// Adapted from http://brandonclapp.com/arranging-an-array-of-flat-paths-into-a-json-tree-like-structure/
var tree = [];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
var currentLevel = tree;
for (var j = 0; j < path.length; j++) {
var part = path[j];
var existingPath = findWhere(currentLevel, 'name', part);
if (existingPath) {
currentLevel = existingPath.children;
} else {
var newPart = {
name: part,
children: [],
}
currentLevel.push(newPart);
currentLevel = newPart.children;
}
}
}
return tree;
function findWhere(array, key, value) {
// Adapted from https://stackoverflow.com/questions/32932994/findwhere-from-underscorejs-to-jquery
t = 0; // t is used as a counter
while (t < array.length && array[t][key] !== value) { t++; }; // find the index where the id is the as the aValue
if (t < array.length) {
return array[t]
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment