js实现数组列表转换多级tree(数组到树)
// 结构
let dataList = [
{id:1,name:"111111111",parentId:0},
{id:2,name:"222222222",parentId:1},
{id:3,name:"333333333",parentId:2},
{id:4,name:"444444444",parentId:3},
{id:5,name:"555555555",parentId:4},
{id:6,name:"666666666",parentId:5},
];
// 处理列表转换树
function handleListTransitionTree(dataList){
const filterChildren = function (data){
let children = dataList.filter(item => +item.parentId === +data.id);
if(children.length > 0){
children.forEach(child => {
child.children = filterChildren(child);
})
}
return children;
}
return dataList.filter(item => {
if(+item.parentId === 0){
item.children = filterChildren(item)
return true;
}
});
}
// 使用
console.log(handleListTransitionTree(dataList))
结果