Skip to content

Instantly share code, notes, and snippets.

@leegcc
Created June 23, 2016 16:06
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 leegcc/73cdae1a8acf46b2d3a77227a797a9b1 to your computer and use it in GitHub Desktop.
Save leegcc/73cdae1a8acf46b2d3a77227a797a9b1 to your computer and use it in GitHub Desktop.
扁平结构转树形结构
function treeify(/*Array*/ flatItems) {
var tree = [], index = {};
flatItems.forEach(function (item) {
var nodes;
if(item.parent){
var parentNode = index[item.parent];
if(!parentNode.nodes){
parentNode.nodes = [];
}
nodes = parentNode.nodes;
} else {
nodes = tree;
}
var node = {
text: item.name
};
index[item.id] = node;
nodes.push(node);
});
return tree;
}
var flatItems = [
{id: "001", name: "aaa", parent: null},
{id: "002", name: "bbb", parent: null},
{id: "003", name: "ccc", parent: "001"},
{id: "004", name: "ddd", parent: "001"},
{id: "005", name: "eee", parent: "002"},
{id: "006", name: "fff", parent: "003"}
];
var tree = treeify(flatItems);
console.log(JSON.stringify(tree));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment