原文链接:https://segmentfault.com/a/1190000018692367
const data = [
{
"area_id": 5,
"name": "广东省",
"parent_id": 0,
},
{
"area_id": 6,
"name": "广州市",
"parent_id": 5,
},
{
"area_id": 7,
"name": "深圳市",
"parent_id": 5,
},
{
"area_id": 4,
"name": "北京市",
"parent_id": 3,
},
{
"area_id": 3,
"name": "北京",
"parent_id": 0,
},
{
"area_id": 2,
"name": "测试子地区",
"parent_id": 1,
},
{
"area_id": 1,
"name": "测试地区",
"parent_id": 0,
}
];
function toTreeData(data,pid){
function tree(id) {
let arr = []
data.filter(item => {
return item.parent_id === id;
}).forEach(item => {
arr.push({
area_id: item.area_id,
label: item.name,
children: tree(item.area_id)
})
})
return arr
}
return tree(pid) // 第一级节点的父id,是null或者0,视情况传入
};
toTreeData(data,0)
输出:
原文:https://www.cnblogs.com/easy5weikai/p/14841057.html