Created
June 23, 2016 16:06
-
-
Save leegcc/73cdae1a8acf46b2d3a77227a797a9b1 to your computer and use it in GitHub Desktop.
扁平结构转树形结构
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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