Skip to content

Instantly share code, notes, and snippets.

@magicapple
Created July 15, 2015 06:03
Show Gist options
  • Select an option

  • Save magicapple/05caf84a25276231e529 to your computer and use it in GitHub Desktop.

Select an option

Save magicapple/05caf84a25276231e529 to your computer and use it in GitHub Desktop.
transform a path array to a tree.
var arr=["www.ifeng.com/index","news.ifeng.com/index","news.ifeng.com/mainland/index","ent.ifeng.com","news.ifeng.com/mil/index","news.ifeng.com/mil/","news.ifeng.com/mil/special/fzlfm/index"];
var item;
var result = [];
var current;
var path;
var hasIt;
var index;
current = result;
for (var i = 0, iLen = arr.length; i < iLen; i++) {
item = arr[i].split('/');
for (var j = 0, jLen = item.length; j < jLen; j++) {
path = item[j];
if (path === '') {
break;
}
hasIt = false;
for (var m = 0, mLen = current.length; m < mLen; m++) {
if (current[m].path === path) {
hasIt = true;
index = m;
break;
}
}
if (j === jLen - 1) {
if (!hasIt) {
current.push({path:path});
}
} else {
if (!hasIt) {
current.push({path:path, list:[]});
index = current.length - 1;
}
if (typeof current[index].list === 'undefined') {
current[index].list = [];
}
current = current[index].list;
}
}
current = result;
}
console.log(JSON.stringify(result));
console.log(result);
[
{
"path": "www.ifeng.com",
"list": [
{
"path": "index"
}
]
},
{
"path": "news.ifeng.com",
"list": [
{
"path": "index"
},
{
"path": "mainland",
"list": [
{
"path": "index"
}
]
},
{
"path": "mil",
"list": [
{
"path": "index"
},
{
"path": "special",
"list": [
{
"path": "fzlfm",
"list": [
{
"path": "index"
}
]
}
]
}
]
}
]
},
{
"path": "ent.ifeng.com"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment