let arr = [
{ id: 2, name: '部门B', parentId: 0 },
{ id: 3, name: '部门C', parentId: 1 },
{ id: 1, name: '部门A', parentId: 2 },
];
function totree(list, parId) {
let obj = {};
let result = [];
//将数组中数据转为键值对结构 (这里的数组和obj会相互引用)
list.map(el => {
obj[el.id] = el;
})
for (let i = 0, len = list.length; i < len; i++) {
let id = list[i].parentId;
if (id == parId) {
result.push(list[i]);
continue;
}
if (obj[id].children) {
obj[id].children.push(list[i]);
} else {
obj[id].children = [list[i]];
}
}
console.log(result)
return result;
}
totree(arr, 0)
var arr1 = [{ id: 1, pid: '-1' }, { id: 11, pid: '1' }, { id: 12, pid: '1' }]
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);
}
}
console.log(tree)
return tree;
}
listToTree(arr1);
function listToTreeWithLevel(list, pid, level) {
var out = []
for (var node of list) {
if (node.pid == pid) {
node.level = level;
var children = listToTreeWithLevel(list, node.id, level + 1)
if (children.length) {
node.children = children
}
out.push(node)
}
}
return out
}
console.log(listToTreeWithLevel(arr1, '-1', 1))
console