# 扁平数组和树形结构的相互转换

Alee

## 扁平数组转换为树形结构

``var arr = [{id: 1, pid: '-1'},{id: 11, pid: '1'},{id: 12, pid: '1'}]``

`map`记录的方法是最常用效果也最好的复杂度是`O(nlgn)`,支持多个根节点:

``````function listToTree(list) {
var map = {}, node, tree= [], i;
for (i = 0; i < list.length; i ++) {
map[list[i].id] = list[i];
list[i].children = [];
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.pid !== '-1') {
map[node.pid].children.push(node);
} else {
tree.push(node);
}
}
return tree;
}

listToTree(arr); //[{"id":1,"pid":"-1","children":[{"id":11,"pid":"1","children":[]},{"id":12,"pid":"1","children":[]}]}]``````

``````function listToTreeWithLevel(list, parent, level) {
var out = []
for (var node of list) {
if (node.pid == parent) {
node.level = level;
var children = listToTreeWithLevel(list, node.id, level + 1)
if (children.length) {
node.children = children
}
out.push(node)
}
}
return out
}

listToTreeWithLevel(arr, '-1', 0) //[{"id":1,"pid":"-1","children":[{"id":11,"pid":"1","children":[],"level":1},{"id":12,"pid":"1","children":[],"level":1}],"level":0}]``````

## 树形结构转换为扁平数组

``````function treeToList(tree) {
var queen = [];
var out = [];
queen = queen.concat(tree);
while(queen.length) {
var first = queen.shift();
if (first.children) {
queen = queen.concat(first.children)
delete first['children'];
}

out.push(first);
}
return out;
}

var tree = [{"id":1,"pid":"-1","children":[{"id":11,"pid":"1","children":[]},{"id":12,"pid":"1","children":[]}]}];
treeToList(tree) //[{"id":1,"pid":"-1"},{"id":11,"pid":"1"},{"id":12,"pid":"1"}]``````

193 声望
7 粉丝