1、源数据
let data = [
{ id: 5, parentId: 2, name: "目录1-1-1", },
{ id: 1, parentId: 0, name: "目录1", },
{ id: 13, parentId: 9, name: "目录2-2-3", },
{ id: 3, parentId: 1, name: "目录1-2", },
{ id: 2, parentId: 1, name: "目录1-1", },
{ id: 12, parentId: 9, name: "目录2-2-2", },
{ id: 4, parentId: 1, name: "目录1-3", },
{ id: 7, parentId: 0, name: "目录2", },
{ id: 9, parentId: 7, name: "目录2-2", },
{ id: 6, parentId: 2, name: "目录1-1-2", },
{ id: 11, parentId: 9, name: "目录2-2-1", },
{ id: 8, parentId: 7, name: "目录2-1", },
{ id: 10, parentId: 7, name: "目录2-3", },
];
2、代码实现
function turnTree() {
let map = {},
result = [];
data.forEach(item => map[item.id] = item);
data.forEach(item => {
const parent = map[item.parentId];
if (parent) {
parent.children = parent.children || [];
parent.children.push(item);
} else {
result.push(item);
}
});
return result;
}
3、函数调用
console.log('turnTree:', turnTree());