Skip to content

Instantly share code, notes, and snippets.

@lsongdev
Created June 16, 2015 05:53
Show Gist options
  • Select an option

  • Save lsongdev/09cd2b267080a1f52a22 to your computer and use it in GitHub Desktop.

Select an option

Save lsongdev/09cd2b267080a1f52a22 to your computer and use it in GitHub Desktop.
var arr = [
{id:1, pid:0, name:"SYSTEM"},
{id:2, pid:1, name:"aa"},
{id:3, pid:2, name:"aaa"},
{id:4, pid:2, name:"b"},
{id:5, pid:0, name:"c"},
{id:6, pid:5, name:"cc"}
];
function generateTree(arr) {
var root = {
name:'root',
items: [],
expanded: true
};
if (arr.length > 0) {
var objMap = {};
arr.forEach(function(item){
var node = {name: item.name};
objMap[item.id] = node;
if(item.pid === 0) {
root["items"].push(node);
} else {
var parent = objMap[item.pid];
parent["expanded"] = true;
parent["items"] = parent["items"] || [];
parent["items"].push(node);
}
});
}
return [root];
}
var json = JSON.stringify(generateTree(arr), null, 2);
document.getElementById("result").innerHTML = json;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment